JsonNode Null JsonArray Parser

Viewed 77

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"},{...}]
}

So, the problem is that customfield_1 is a JsonArray and sometimes it can be 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. How to avoid it ?

2 Answers

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

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:

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

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyObject jsonObj = mapper.readValue(jsonString, MyObject.class);
Related