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

Question:

{
"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 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.

Answer:

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 ( https://mvnrepository.com/artifact/org.json/json/20180813 ) 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
AllEscort