Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...