1

Working on JSON for the first time. The problem is -

I am getting null pointer exception even after handling the empty json array. I have created a josn file file in which there is an empty array. my json file is like-

{
   "name" :"jsonObject",

   "myArray" : []
}

For parsing I am using json.simple-1.1.1.jar. My java code is -

JSONParser parser = new JSONParser();
        JSONObject rootObj = (JSONObject) parser.parse(new FileReader(filePath));           

        String str = (String) rootObj.get("name");

        JSONArray array = (JSONArray)rootObj.get("array");

        if(array.isEmpty())
            System.out.println("array is null");

In json file the array will be null sometimes and sometimes not. What is the proper way to handle it?

2
  • Maybe it's just a copy-paste typo, but shouldn't it be rootObj.get("myArray")? Commented Apr 23, 2014 at 12:26
  • so stupid of me!!.... Commented Apr 23, 2014 at 12:29

1 Answer 1

2

Your member's name is myArray not array. This works:

JSONArray array = (JSONArray) rootObj.get("myArray");

To check if the member is there use has():

if(rootObj.has("myArray")) {
    JSONArray array = rootObj.getJSONArray("myArray"); // getJSONArray avoids cast :-)
    // ...
}

See: http://www.json.org/javadoc/org/json/JSONObject.html#has%28java.lang.String%29

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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