我一直在嘗試解析JSON具有以下格式與可選字段處理以JSON
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();
}
現在,問題是...... foo和陣列是可選字段....有時它是存在的。 。othertimes不..
我認爲這將工作..除了taht我看到在上面的代碼塊註釋顯示空指針錯誤..
Error:
java.lang.NullPointerException
at org.hadoop.Foo$MapClass.map(Foo.java:48)
任何例如JSON
{ "_id" : "foobar", "foo" : null }
{ "_id" : "foobar", "foo" : null , "bar":[{"id":1}]}
{ "_id" : "foobar"}
{ "_id" : "foobar", "foo" : 23 }
什麼是你試圖解析的JSON樣子? –
@JustinJasmann:edited .. :) – Fraz
問題是,你正試圖''toString()'null'。對於一個解決方案,你可以參考Sotirios的回答:) –