How to create a JSON array?

Hi, I want to create a JSON array.

I tried using:

JSONArray jArray = new JSONArray(); while(itr.hasNext()){ int objId = itr.next(); jArray.put(objId, odao.getObjectName(objId)); } results = jArray.toString(); 

Note: odao.getObjectName(objId) retrieves the name based on the "object identifier" called objId.

However, I get a very funny look, like

 [null,null,null,"SomeValue",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"AnotherValue",null,null,null,null,null,null,null,null,null,null,"SomethingElse","AnotherOne","LastOne"] 

If only "LastOne" is displayed when I retrieve it using jQuery .

The array should look like

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

The numbers are not displayed for any reason in the array I get.

+5
source share
3 answers

For a quick fix:

 JSONArray jArray = new JSONArray(); while (itr.hasNext()) { JSONObject json = new JSONObject(); int objId = itr.next(); json.put(Integer.toString(objId), odao.getObjectName(objId)); jArray.put(json); } results = jArray.toString(); 

Based on TJ Crowder , my solution does this:

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

Refer to Jim Blackler's comment on what you are doing wrong.

+12
source

The key is in the documentation for JSONArray for the put method (int index, String value)

If the index is longer than the JSONArray, then null elements will be added if necessary.

+8
source

What you specified for your "Object should look like this" is invalid JSON. This is an object (limited by { and } ), but then it has values ​​inside it that have no keys. See json.org for JSON syntax.

If you want to:

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

... instead of JSONObject and turn your objId into keys when entering entries, for example:

 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 to:

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

... see Elite Gentleman's answer (which is JSONArray from JSONObjects).

+2
source

All Articles