How do I create a JSON Array?

后端 未结 3 1400
[愿得一人]
[愿得一人] 2021-01-13 06:31

Hi I want to create a JSON array.

I have tried using:

JSONArray jArray = new JSONArray();
  while(itr.hasNext()){
    int objId = itr.next();
jArray.         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 07:02

    What you've quoted for your "The object should look like" is invalid JSON. It's an object (delimited by { and }) but then it has values within it that don't have any keys. See json.org for the syntax of JSON.

    If you want this:

    {"3":"SomeValue",
     "40":"AnotherValue",
     "23":"SomethingElse",
     "9":"AnotherOne",
     "1":"LastOne"
    }
    

    ...use JSONObject instead, and turn your objIds into keys when putting the entries in, e.g.:

    JSONObject obj = new JSONObject();
    while(itr.hasNext()){
        int objId = itr.next();
        obj.put(String.valueOf(objId), odao.getObjectName(objId));
    }
    results = obj.toString();
    

    If you want this:

    [{"3":"SomeValue"},
     {"40":"AnotherValue"},
     {"23":"SomethingElse"},
     {"9":"AnotherOne"},
     {"1":"LastOne"}
    ]
    

    ...see The Elite Gentleman's answer (that's a JSONArray of JSONObjects).

提交回复
热议问题