JsonNode 空 JsonArray 解析器 [英] JsonNode Null JsonArray Parser

查看:100
本文介绍了JsonNode 空 JsonArray 解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JsonNode 响应 ( unirest ),我想使用 JSON Parser 对其进行解析.

I am having a JsonNode response ( unirest ) which I want to parse using JSON Parser.

现在,假设结构有点像这样:

Now, let's say the structure is somewhat like this :

{
"expand" : "names",
"customfield_1" : null,
"customfield_2" : [ { "email":"123@gmail.com"},{...}]
}

所以,问题在于 customfield_1 是一个 JsonArray,有时它可以为 null.

So, the problem is that customfield_1 is a JsonArray and sometimes it can be null.

所以,只要我使用

JSONArray myArr = myObj.getJSONArray("customfield_1")

我收到以下错误:

org.json.JSONException: JSONObject["customfield_1"] is not a JSONArray.

我尝试更改为 JsonObject 和 JsonString 但它们也没有帮助.如何避免?

I tried to change to JsonObject and JsonString but they also didn't help. How to avoid it ?

推荐答案

你可以在获取数组之前显式检查字段是否为null:

You can explicitly check if the field is null before getting the array:

JSONArray myArr = myObj.isNull("field") ? null : myObj.getJSONArray("field");


包含您的数据的完整示例:

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);

输出:

null
[{"email":"123@gmail.com"},{"email":"abc@gmail.com"}]

这篇关于JsonNode 空 JsonArray 解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆