frazman
frazman

Reputation: 33293

Dealing with optional field in json

I have am trying to parse a json with following format

JSONObject json;
        try {
            json = (JSONObject)parser.parse(value.toString());

            String foo = (String) json.get("foo").toString();//error here
            String id1 = (String) json.get("_id");

            JSONArray array = (JSONArray)json.get("bar");
            } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Now, the issue is ...foo and array are optional field.... Sometimes it is present.. othertimes not..

I thought this would work.. except taht I am seeing nullpointer error indicated by comment in above code block..

Error:
java.lang.NullPointerException
    at org.hadoop.Foo$MapClass.map(Foo.java:48)

Any example json

{ "_id" : "foobar", "foo" : null }
{ "_id" : "foobar", "foo" : null , "bar":[{"id":1}]}
{ "_id" : "foobar"}
{ "_id" : "foobar", "foo" : 23 }

Upvotes: 1

Views: 11822

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280142

JSONObject from simple json implements a Map, you can just check that the return value of get is not null before using it.

However, this is also a limitation of the API. You cannot tell if the null originates from the JSON or from the lack of JSON value with get(String).

As JB Nizet stated in the comments, you can use containsKey(Object) to make that distinction.

Upvotes: 4

Related Questions