Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a JSON Array?

Hi I want to create a JSON array.

I have 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 a name based on the "object Id" which is called objId.

However I get a very funny looking array 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"]

With only "LastOne" being displayed when I retrieve it using jQuery.

The Array SHould look like

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

The numbers aren't showing up at all for some reason in the array that I am getting.

like image 912
Ankur Avatar asked Mar 30 '10 09:03

Ankur


People also ask

How do you create arrays in JSON?

jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.

Can a JSON file be an array?

JSON can be either an array or an object.

What is the difference between an array and JSON?

JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.

What is difference in [] and {} in JSON?

They don't have the same meaning at all. {} denote containers, [] denote arrays.


1 Answers

For your quick Solution:

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 T. J. Crowder's response, my solution does this:

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

Refer to Jim Blackler's comment of what you're doing wrong.

like image 151
Buhake Sindi Avatar answered Nov 15 '22 06:11

Buhake Sindi