Search code examples
javajsonannotationsjacksonoval

How to detect missing field when converting jsonObject to Model Object


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.

}

Solution

  • 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