Create key-value pairs string in JSON

前端 未结 3 823
渐次进展
渐次进展 2020-12-19 20:53

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)

[{
          


        
相关标签:
3条回答
  • 2020-12-19 21:17

    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]
    
    0 讨论(0)
  • 2020-12-19 21:31

    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.

    0 讨论(0)
  • 2020-12-19 21:35

    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".

    0 讨论(0)
提交回复
热议问题