Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - Create key-value pairs string in JSON

I'm new to JSON. I'm trying to create a JSON string in Java (org.json.JSONObject(json.jar)) which resembles like (basically a set of name-value pairs)

[{
    "name": "cases",
    "value": 23
}, {
    "name": "revenue",
    "value": 34
}, {
    "name": "1D5",
    "value": 56
}, {
    "name": "diag",
    "value": 14
}]

Can anyone help me on how to create this in Java? I want the name and value to be in each so that i can iterate over the collection and then get individual values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:

new JSONArray()
    .put(new JSONObject()
            .put("name", "cases")
            .put("value", 23))
    .put(new JSONObject()
            .put("name", "revenue")
            .put("value", 34))
    .put(new JSONObject()
            .put("name", "1D5")
            .put("value", 56))
    .put(new JSONObject()
            .put("name", "diag")
            .put("value", 14))
    .toString();

Once you have the final array, call toString on it to get the output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...