1

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?
Pavan
  • 543
  • 4
  • 16

1 Answers1

0

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("");
}
Beppe C
  • 11,256
  • 2
  • 19
  • 41
  • 2
    Whatever you said was true. But I found this now. https://json-schema.org/implementations.html this will help for any kind of validations in the JSON. It has great support as well. Check that once. – Pavan Jan 15 '20 at 09:27