Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON file in Java using json-simple

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.

like image 232
George Avatar asked Dec 06 '25 14:12

George


2 Answers

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);
}
like image 62
Jeremy Hanlon Avatar answered Dec 08 '25 03:12

Jeremy Hanlon


The object in your file has exactly one property, named numbers.
There is no natural property.

You probably want to examine the objects inside that array.

like image 39
SLaks Avatar answered Dec 08 '25 04:12

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!