sashi
sashi

Reputation: 31

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.

Upvotes: 3

Views: 27004

Answers (3)

Mihai
Mihai

Reputation: 659

Try to use gson if you have to work a lot with JSON in java. Gson is a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Here is a small example:

Gson gson = new Gson();
gson.toJson(1);            ==> prints 1
gson.toJson("abcd");       ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values);       ==> prints [1]

Upvotes: 0

Brigham
Brigham

Reputation: 14554

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.

Upvotes: 13

Hot Licks
Hot Licks

Reputation: 47749

What you've got there is a JSON array containing 4 JSON objects. Each object contains two keys and two values. In Java a JSON "object" is generally represented by some sort of "Map".

Upvotes: 0

Related Questions