George
George

Reputation: 194

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.

Upvotes: 3

Views: 19864

Answers (3)

DaVinziBoi
DaVinziBoi

Reputation: 33

Adding on to @Jermey Hanion's answer and comment, here is what I did to get "imaginary" and "natural"

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");
    JSONObject complex = (JSONObject) jsonNumber.get("complex");
    String imaginary = (String) complex.get("imaginary");
    System.out.println(natural);
}

Jeremey's answer for getting imaginary is not correct, or maybe it was correct. The above snippet is to my knowledge working on my project.

PS. Sorry for reviving the thread but I thought it would be a useful resource for people looking to learn JSON.simple

Upvotes: 0

Jeremy Hanlon
Jeremy Hanlon

Reputation: 317

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);
}

Upvotes: 4

SLaks
SLaks

Reputation: 888177

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.

Upvotes: 3

Related Questions