'How to convert a @requestBody to a customized object?

I am using springboot controller with @RequestBody. I have following json request body

{
  "abc":"xyz",
  "valid":"yes"
}

I have a corresponding POJO

class MyObject{
  private String abc;
  private Boolean valid;
}

I have controller like

@PostMapping(value = "somePath", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MyResponse>  myMethod(@RequestBody MyObject request)  {

Obviously it won't work because valid is a string in request whereas it is boolean in MyObject. I want it to have a logic so if valid=yes is in request it will be converted to boolean true in MyObject. Any mechanism does spring has to achieve that?



Solution 1:[1]

It is possible if you annotate your MyObject with jackson annotations: in this case you can create an all args constructor with the JsonCreator annotation and define there your expected behaviour:

public class MyObject {

    private String abc;
    private Boolean valid;

    @JsonCreator
    public MyObject(String abc, String valid) {
        this.abc = abc;
        if (valid.equals("yes")) {
            //be aware valid will remain null 
            //if valid is different from yes
            this.valid = true; 
        }
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1