java – How to verify if a certain field / value exists in a JSON document?



My application receives the JSON that above, in this Json there is the array "gtw_info", but as you can see the data in this array is not always the same for each position. I would like to know how I can check when the field "gps_tmst", for example, exists or not in the array.


Using the Gson API, ideally you would create a POJO class that maps all of your json fields. From there, it would be enough for you to check if a certain field is null. Here you'll find a basic example of how to do it, but there are dozens of tutorials available on the internet.

However, if this solution is not what you are looking for, you can add a lib called Json ( ) to your project and, using it, create an object Json and then browsing through the created object, check whether what you are looking for exists or not.

It would be something like this:

JSONObject json = new JSONObject(seu_json_em_formato_String);
if(json.has("gtw_info")) {
  JSONArray array = json.getJSONArray("gtw_info"); //recuperando gtw_info
    for (int i = 0; i < array.length(); i++) {
      JSONObject object = array.getJSONObject(i); //cada objeto dentro de gtw_info
      if(object.has("gtw_id")) { //finalmente checa se o campo existe
      //sua logica aqui

If there is any doubt, just ask.

Scroll to Top