I am sending a JsonObject
using web service. The method that receives the call has a method parameter of model Object for the corresponding JsonObject
Input being passed. The JsonObject
is successfully getting converted to model object but I am not able to test a few of my Responses from the model Object.
For example: if any mandatory field is missing in the input JSON or if any field in the input JSON is set to null
, then in both these cases the model object field is coming out to be null
.
I am not able to detect if the null
is because of field missing or the field being set to null
.
Can anybody suggest me a solution?
My last way out for this is, I will receive method parameter input as String
and not my model Object and then using conditional checks, check the input string and get my Responses accordingly. But my JSON input object is very large and I am hoping there could be a better way out than this.
It is a Spring boot project.
Code Snippet:
JSON Object being sent
{"orgType":null, "orgLocation": "Geneva" , //other fields}
@RequestMapping(value="/addOrganizations", method= RequestMethod.POST)
public ResponseEntity addOrganization(@RequestBody Organization organization){
// code goes here
}
If I try with
{"orgType":null, "orgLocation": "Geneva" , //other fields}
or:
{"orgLocation": "Geneva" , //other fields}
and check with debugger inside addOrganization()
method, then the value is null
in both the cases.
Model class:
public class Organization{
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String orgType;
private String orgLocation;
// other fields and getters and setters.
}
You can get the object from the JSON with the help of JSONObject. get() method and then using the instanceof operator to check for the type of Object. Note that it may be Integer or Long ; Float or Double .
Return valueJsonObject::isNull() returns a bool that tells if the JsonObject points to something: true if the JsonObject is null, false if the JsonObject is valid and points to an object.
JsonObject::containsKey() returns a bool that tells whether the key was found or not: true if the key is present in the object. false if the key is absent of the object.
Ignoring unknown properties using @JsonIgnoreProperties If you are creating a Model class to represent the JSON in Java, then you can annotate the class with @JsonIgnoreProperties(ignoreUnknown = true) to ignore any unknown field.
I was going through the links of StackOverflow and finally got an answer through this link
Jackson: What happens if a property is missing?
Thought might be helpful for somebody else.
Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With