0

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.

2
  • I tried validating the JSON you're using at jsonlint.com and it says it's not valid. Is "["flowrate":{"mod":0,"value":110},"command":{"cancel":0,"start":0}] " the JSON that's in your myfile.json? Commented Apr 22, 2018 at 15:43
  • you are right. My mistake that i kind of wrote it from memory. it was missing { } final enclosure Commented Apr 22, 2018 at 15:53

2 Answers 2

1

I also could not validate your JSON. I made an assumption that you wanted to create an array of two objects (flowrate and command) and fixed the JSON:

    String value = "[{\"flowrate\":{\"mod\":0,\"value\":110}},{\"command\":{\"cancel\":0,\"start\":0}}]";
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(value);
    JSONArray array=(JSONArray)obj;
    JSONObject jo = (JSONObject) array.get(1);
    System.out.println(jo.get("command"));

which gives the following output:

{"cancel":0,"start":0}

Process finished with exit code 0
Sign up to request clarification or add additional context in comments.

1 Comment

your example works, but i still can't understand why the same stupid json refuses to work when it is parsed from file. man, it gets frustrating :))
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.