title: Dealing with optional field in json
body: <p>I have am trying to parse a json with following format</p>
  
  <pre><code>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();
          }
  </code></pre>
  
  <p>Now, the issue is ...foo and array are optional field.... Sometimes it is present.. othertimes not..</p>
  
  <p>I thought this would work.. except taht I am seeing nullpointer error indicated by comment in above code block..</p>
  
  <pre><code>Error:
  java.lang.NullPointerException
      at org.hadoop.Foo$MapClass.map(Foo.java:48)
  </code></pre>
  
  <p>Any example json</p>
  
  <pre><code>{ "_id" : "foobar", "foo" : null }
  { "_id" : "foobar", "foo" : null , "bar":[{"id":1}]}
  { "_id" : "foobar"}
  { "_id" : "foobar", "foo" : 23 }
  </code></pre>