AncientSwordRage
AncientSwordRage

Reputation: 7615

Why does my JSON-Simple JSONArray give me a nullpointer exception?

I'm following this tutuorial here, and my JSON object is near enough the same, except I have this sort of format:

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}

Here is my relevant code:

Object obj = parser.parse(new FileReader("exampleJson.json"));

JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");

Then my program goes off an gets the values form the keys etc. Or it would but I get a NullPointerException from eclipse. Why is this?

It should unpackage my .json file into jsonObject, unpackage the "user" key as a JSONObject user, then unpackage the "SomeList" key as a JSONArray called list. Except when it does so it must be trying to put one of val1 or val2 into a part of the JSONArray that does not exist and just points into the abyss of null. What have I done to deserve this wrong ?

How do I fix my program?

Upvotes: 0

Views: 2019

Answers (2)

aymeric
aymeric

Reputation: 3895

Using the exact same json file:

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}

Here is the code I use (with the imports to really make sure we have the same ones):

import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Test {

    public static void main(String[] args) throws Exception {
        Object obj = new JSONParser().parse(new FileReader("t.json"));

        JSONObject jsonObject = (JSONObject) obj;
        JSONObject user = (JSONObject) jsonObject.get("user");
        JSONArray list = (JSONArray) user.get("SomeList");
        System.out.println(list);
    }
}

And here is the output:

["val1","val2"]

I used maven and m2e to import the library. The version used for this test was json-simple-1.1.jar.

Upvotes: 1

Ilya
Ilya

Reputation: 29693

Your code is working well for me

public class App {

    public static void main(final String[] args) throws FileNotFoundException, IOException, ParseException {
        final Object obj = new JSONParser().parse(new FileReader("D:/a.json"));
        final JSONObject jsonObject = (JSONObject) obj;
        final JSONObject user = (JSONObject) jsonObject.get("user");
        final JSONArray list = (JSONArray) user.get("SomeList");
        System.out.println(list);
    }
} 

File D:/exampleJson.json

{"user":{
    "SomeKeys":"SomeValues",
    "SomeList":["val1","val2"]
    }
}  

output is

["val1","val2"]

Upvotes: 1

Related Questions