Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check on field in JSON for null?

Tags:

java

json

I have below JSON response in which I need to check whether response field has null value or not. If response field has null value then I need to exit out of the program.

[
    {
        "results": {
            "response": null,
            "type": "ABC"
        },
        "error": null
    }
]

What is the easiest way to check this out? One option I know is to convert JSON to POJO and then check response field. Is there any other way?

like image 924
user1950349 Avatar asked Dec 14 '22 07:12

user1950349


1 Answers

If you are using codehouse's JSON library , you could do something like this:

    JSONObject jsonObj = new JSONObject(jsonString);        
    System.out.println(jsonObj .isNull("error") ? " error is null ":" error is not null" );

if using Google's gson :

JsonObject jsonObject = new JsonParser().parse(st).getAsJsonObject();
JsonElement el = jsonObject.get("error");
if (el != null && !el.isJsonNull()){
        System.out.println (" not null");           
}else{
        System.out.println (" is null");
}
like image 101
JavaHead Avatar answered Dec 16 '22 19:12

JavaHead