'Java getJSONArray when it is set to null

The problem happens when I'm trying to get children of a comment. If the child key is null, my application crashes and gives me this error:

org.json.JSONException: Value null at child of type org.json.JSONObject$1 cannot be converted to JSONArray

I tried this code but it doesn't work:

 if (comments.getJSONObject(i).getJSONArray("child") != null) {child = comments.getJSONObject(i).getJSONArray("child");

What should I do?



Solution 1:[1]

if (comments.getJSONObject(i).getJSONArray("child")

Replace

if(comments.isNull(comments.getJSONObject(i).getJSONArray("child")));

Solution 2:[2]

  • First, i think you should confirm that with your backed, define witch field can be null or not.

  • Second, if all field can be null, you can use more powerful lib for decode json information, like [Gson](https://github.com/google/gson), it can help you deal the null fields without exception.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Codemaker
Solution 2 xuefeng wei