Parse JSON file in Java: getJSONObject(int) is undefined

s.dragos

I`m trying to fetch some values fron a JSON file using:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONArray array= new JSONArray();
array.add(obj); 

If I run: System.out.println(array); , the output is

[{"flowrate":{"mod":0,"value":110},"command":{"cancel":0,"start":0}}] 

, which is my json file. My problem is how to get value from a specific field, let's say the value of "comand":"cancel".

I've tried JSONObject myitem = array.getJSONObject(1).getJSONObject("cancel"); with no success (error: getJSONObject(int) is undefined for the type JSONArray).

I mention that I'm using the json-simple toolkit.

s.dragos

After many hours of searching, I discovered that there is big difference between { } and [ ], therefore differnent methodes to parse them:

enter image description here

In my case:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONObject jsonObject =  (JSONObject) json;
JSONObject command= (JSONObject) jsonObject.get("command");
System.out.println("command: " + command);
long cancel= (Long) command.get("cancel");
System.out.println("cancel: " + cancel);

Here you'll find the best example for nested json objects

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related