user5123481566
user5123481566

Reputation: 63

How do I parse a JSON List in Java whose elements are all named?

I have a JSON String of the type below:

{
  "entry_1" : {
     "value_1":"a",
     "value_2":"b",
     "value_3": [ "c" ],
  },
  "entry_2" : {
     "value_1":"d",
     "value_2":"e",
     "value_3": [ "f" ],
  },

  ...
}

The entries entry_1, entry_2, entry_... are weird because it looks like they form a list, but when I try to parse them into a JSONArray I get the exception:

org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

My code to parse this string is:

JSONParser parser = new JSONParser();
JSONArray array = (JSONArray) parser.parse(new FileReader(myFile));

for (Object obj : array)
{
    JSONObject jsonObj = (JSONObject) obj;
    
    // Do stuff with jsonObj
}

How do I parse this strange JSON?

Thanks a lot!

Upvotes: 1

Views: 497

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83537

The entries entry_1, entry_2, entry_... are weird because it looks like they form a list, but when I try to parse them into a JSONArray I get the exception:

The names of the keys don't matter here. Since the JSON is surrounded with {}, you have an object here, not an array. So you should parse it as an object:

JSONObject object = (JSONObject) parser.parse(new FileReader(myFile));

With that said, you are correct that an array would be more appropriate here since the keys are just numbered anyway.

Upvotes: 1

Related Questions