Best practice to check contains key and check for null/empty in JSON?

658 Views Asked by At

I will receive the following JSON request to my service.

{
  "city" : "Hyderabad",
  "state" : "Telangana",
  "country" : "India"
}

Sometimes In the request, I might not get the city field or city field might be empty which is not expected. So, I'm handling that in the following way:

payload is my request JSON.

if ( payload.has("city") && !payload.get("city").equals("") )

I'm handling it in the above way. But the problem is that If I add new mandatory again then I need to add two more conditions as:

if ( payload.has("city") && !payload.get("city").equals("") && payload.has("newKey") && !payload.get("newKey").equals("") )
  1. check whether the key is available or not.
  2. check whether the value is not empty.

    Is there any best practice to solve this?
1

There are 1 best solutions below

1
Beppe C On

I would deserialize the JSON payload into an object, then you can use the combination of getters as you like.

MyObj toValue = mapper.readValue(parser, MyObj.class);

If you want to stick to your original approach I would then create some helper methods to make it all more readable:

private boolean hasCity(String payload) {
   return payload.has("city") && !payload.get("city").equals("");
}