How to check if a given field / value exists in the JSON document?

3
{
"timestamp":"2018-10-08T16:58:38.949Z",
"dataFrame":"QQ==",
"fcnt":15,
"freq":902500000,
"port":12,
"rssi":-69,
"snr":10,
"sf_used":10,
"session_id":"f41e10e8-1c73-499c-8ad7-4cbcd54c8ebd",
"gtw_info":[{
    "gtw_id":"000000000b0319a3",
    "rssi":-69,
    "snr":10},
    {
    "gtw_id":"000000000b031938",
    "rssi":-100,
    "snr":10.2,
    "gps_tmst":1539014318485}],
"id":1539017918949,
"dr_used":"SF10BW125",
"decrypted":true}

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

    
asked by anonymous 09.10.2018 / 17:49

1 answer

1

Using the Gson API, ideally you would create a POJO class that mapped all the fields of your json. From there, you just have to check if a given field is null. Here you find a basic example of how to do, but there are dozens of tutorials available on the internet.

However, if this is not the solution you are looking for, you can add a lib named Json to your project ( link ) and, using it, create a Json object and then navigate through the created object, check if 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 doubt, just ask.

    
09.10.2018 / 19:12