Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create key-value pairs string in JSON

Tags:

java

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.

like image 582
sashi Avatar asked Apr 22 '26 14:04

sashi


1 Answers

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.

like image 106
Brigham Avatar answered Apr 24 '26 05:04

Brigham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!