How do I verify that a given field/value exists in the JSON document?

Asked

Viewed 2,872 times

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 there is the array "gtw_info", but as you can notice the data of this array are not always the same for each position. I wonder how I can check when the "gps_tmst" field, for example, exists or not in the array.

  • Are you using some library for treatment?

  • I’m using Gson, but I haven’t found anything related to my need so far.

  • if you’re using gson you could just turn it into an object and treat it normally

1 answer

1


Using the Gson API, the ideal would be for you to create a POJO class that maps all fields in your json. From there, just check if a certain 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 solution is not the one you are looking for, you can add to your project a lib called Json (https://mvnrepository.com/artifact/org.json/json/20180813) and, using it, create a Json object and then navigating the created object, check whether what you’re 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’s any doubt, just ask.

  • THANK YOU VERY MUCH! It worked exactly as I needed it. : D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.