0

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So how can I make move to the next JSON object?
You should make sure the input follows the 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.
It actually had [], but an exception was thrown: Syntax error, insert "}" to complete Block, so I removed them. I think I got it. Thanks.
2

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 { }.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.