I have this JSON file that is read and stored in a String called jsonString and it looks like this:
{
"position":1,
"team_id":10260,
"home":
{
"played":18,
},
},
{
"position":2,
"team_id":8456,
"home":
{
"played":12,
},
},
Code for parsing:
JSONObject obj = new JSONObject(jsonString);
Iterator it = obj.keys();
while(it.hasNext()){
String s = it.next().toString();
System.out.print(s + " " + obj.getString(s) + " ");
}
Output is: position 1 home {"played":18} team_id 10260
So it doesn't read the rest of the file. Can you tell me what is the problem? And also, why home {"played":18} is printed before team_id 10260?
2 Answers 2
If you look at the way your brackets are organized, you can see that your String actually contains several JSON objects, and the construction stops after the first complete one.
As for your second question, Iterators seldom have a guaranteed order, so you can't make any assumptions about which order the elements will be returned in.
3 Comments
JSON object?JSON standard format. How to do this depends on where you are getting your indata. It looks like what you have is an array, and in that case you need to add a [ to the start and a ] at the end of the data.[], but an exception was thrown: Syntax error, insert "}" to complete Block, so I removed them. I think I got it. Thanks.The order will be dependent on the type of Map that JSONObject uses; could be indeterminate, or could be by the key's codepoint, or could be in order read, depending on, e.g. HashMap, TreeMap or LinkedHashMap.
Other than that, there are two objects serialized and JSONObject has apparently just stopped after the first one. You may need to wrap the entire input in a set of { }.