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.
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.
JSON can be either an array or an object.
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.
They don't have the same meaning at all. {} denote containers, [] denote arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With