[英]JsonNode Null JsonArray Parser
I am having a JsonNode response ( unirest ) which I want to parse using JSON Parser.我有一个 JsonNode 响应( unirest ),我想使用 JSON 解析器解析它。
Now, let's say the structure is somewhat like this:现在,假设结构有点像这样:
{
"expand" : "names",
"customfield_1" : null,
"customfield_2" : [ { "email":"123@gmail.com"},{...}]
}
So, the problem is that customfield_1
is a JsonArray and sometimes it can be null.所以,问题在于
customfield_1
是一个 JsonArray,有时它可能是 null。
So, as soon as I use所以,一旦我使用
JSONArray myArr = myObj.getJSONArray("customfield_1")
I get the following error:我收到以下错误:
org.json.JSONException: JSONObject["customfield_1"] is not a JSONArray.
I tried to change to JsonObject and JsonString but they also didn't help.我试图更改为 JsonObject 和 JsonString 但它们也没有帮助。 How to avoid it?
如何避免?
You can explicitly check if the field is null
before getting the array:您可以在获取数组之前显式检查该字段是否为
null
:
JSONArray myArr = myObj.isNull("field") ? null : myObj.getJSONArray("field");
Complete example with your data:包含您的数据的完整示例:
String jsonString = "{\n" +
"\"expand\" : \"names\",\n" +
"\"customfield_1\" : null,\n" +
"\"customfield_2\" : [ { \"email\":\"123@gmail.com\"},{ \"email\":\"abc@gmail.com\"}]\n" +
"}";
JSONObject myObj = new JSONObject(jsonString);
JSONArray myArr1 = myObj.isNull("customfield_1") ? null : myObj.getJSONArray("customfield_1");
JSONArray myArr2 = myObj.isNull("customfield_2") ? null : myObj.getJSONArray("customfield_2");
System.out.println(myArr1);
System.out.println(myArr2);
Output: Output:
null
[{"email":"123@gmail.com"},{"email":"abc@gmail.com"}]
Using object mapper, you can read json and setting deserialization feature FAIL_ON_UNKNOWN_PROPERTIES
as false can handle this scenario使用 object 映射器,您可以读取 json 并将反序列化功能
FAIL_ON_UNKNOWN_PROPERTIES
设置为 false 可以处理这种情况
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyObject jsonObj = mapper.readValue(jsonString, MyObject.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.