3

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":"[email protected]"},{...}]
}

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 2

2

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\":\"[email protected]\"},{ \"email\":\"[email protected]\"}]\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":"[email protected]"},{"email":"[email protected]"}]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.