Parsing a JSON file in Java using json-simple

George picture George · Apr 1, 2016 · Viewed 13.2k times · Source

I have created a .json file:

{
  "numbers": [
    {
      "natural": "10",
      "integer": "-1",
      "real": "3.14159265",
      "complex": {
        "real": 10,
        "imaginary": 2
      },
      "EOF": "yes"
    }
  ]
}

and I want to parse it using Json Simple, in order to extract the content of the "natural" and the "imaginary".

This is what I have written so far:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
String natural = (String) jsonObject.get("natural");
System.out.println(natural);

The problem is that the value of natural is "null" and not "10". Same thing happens when I write jsonObject.get("imaginary").

I have looked at many websites (including StackOverflow), I have followed the same way most people have written, but I am unable to fix this problem.

Answer

Jeremy Hanlon picture Jeremy Hanlon · Apr 1, 2016

You need to find the JSONObject in the array first. You are trying to find the field natural of the top-level JSONObject, which only contains the field numbers so it is returning null because it can't find natural.

To fix this you must first get the numbers array.

Try this instead:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");

for (Object number : numbers) {
    JSONObject jsonNumber = (JSONObject) number;
    String natural = (String) jsonNumber.get("natural");
    System.out.println(natural);
}