Reputation: 2079
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
?
Upvotes: 0
Views: 73
Reputation: 64026
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 {
}
.
Upvotes: 2
Reputation: 46219
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, Iterator
s seldom have a guaranteed order, so you can't make any assumptions about which order the elements will be returned in.
Upvotes: 4