4

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?

user1950349
  • 4,738
  • 19
  • 67
  • 119
  • 1
    If it is String, you may try to apply regex. http://www.rexegg.com/regex-quickstart.html – kosa Mar 25 '16 at 20:08

5 Answers5

12

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");
}
JavaHead
  • 635
  • 1
  • 6
  • 21
1

I am using org.json.JSONObject. This is an example that you can use to test a JSONObject is null or not.

package general;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class CheckNullInJSONObject {

    public static void main(String[] args) {
        JSONObject json = new JSONObject("{results : [{response:null}, {type:ABC}], error:null}");
        JSONArray array = json.getJSONArray("results");
        try {
          for(int i = 0 ; i < array.length() ; i++){
            JSONObject response = array.getJSONObject(i);
            if (response.isNull("response")){
                throw new Exception("Null value found");
            }
          }
        }catch (Exception e) {
          e.printStackTrace();
        }
    }
}
Suparna
  • 1,132
  • 1
  • 8
  • 20
0

Regex/parse string to get the response field value or use google gson lib: https://github.com/google/gson to create object and access any field.

Tokazio
  • 516
  • 2
  • 18
0

The safest way to reliably check the value of the response field for null is (as you suggested) to model the json data structure with POJO classes and use a json library such as Gson or Jackson to deserialize your json to your POJOs.

Don't listen to other answers here advising the use of regex. Building a correct and reliable json parser using only regex is a) bug prone and b) can have poor performance.

Asaph
  • 159,146
  • 25
  • 197
  • 199
0

Two ways depending on your needs:

Quick and dirty way which might actually be useful/good enough/good performance:

String jsonString = ...
jsonString.contains("\"response\": null");

Yes, it's error prone if the server changes anything, even line breaks etc. But it will be using a lot less resources.

Variations with higher tolerance include regexp that simply allow zero or multiple whitespace between field name and value. Another variant is to find the index of the field and look for the value after that manually:

int fieldIndex = jsonString.indexOf("\"response\":");
//left as an exercise...

Json parsing with a library, such as Gson (Google's json library):

Simple minimum Results class:

public static class Result { 
    public static class Results {
      public String response;
    }
    public Results results;
}

Parse and check (ignoring null and length check of array):

Gson gson = new Gson();
Result[] results = gson.fromJson(jsonString, Result[].class);
System.out.println(results[0].results.response);

Gson can be found here: https://github.com/google/gson

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49