我正在尝试解析具有以下格式的 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 和数组是可选字段……有时它存在……有时不存在……
我认为这会工作..除了我看到上面代码块中的注释指示的空指针错误..
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 }
最佳答案
JSONObject
from simple json
implements a Map
,你可以在使用它之前检查 get
的返回值不为 null
。
但是,这也是 API 的一个限制。您无法判断 null
是来自 JSON 还是来自 get(String)
缺少 JSON 值。
As JB Nizet stated in the comments , 你可以使用 containsKey(Object)
做出这种区分。
关于java - 处理json中的可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325382/