Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non Required JSON attribute in Spring (Jackson Mapping)

I have this function in a Spring controller:

@RequestMapping(value = "/*", method = RequestMethod.POST)
@ResponseBody
@Consumes("application/json")
public JSONresponse alta(@RequestBody JSONrequest parametros, HttpServletRequest request) {
   some code...}

JSON request is a JavaClass like this:

public class JSONrequest {
      private String code;
      private String message;
      //getters and setter}

I'm using Jackson to map this, and works correctly. But my question is: It's possible make message attribute non required? I would like the web service to accept JSON with both attributes or only with the "code" attribute

like image 781
colomer7 Avatar asked Feb 17 '26 21:02

colomer7


1 Answers

You can use required property of JsonProperty. But this property is available from 2.7.x or higher versions.

public class JSONrequest {

      @JsonProperty(value ="CODE",required = true)
      private String code;

      @JsonProperty(value ="MESSAGE",required = false)
      private String message;

Above example makes code attribute as mandatory while message as an optional field for deserialization.

like image 90
Amit Bhati Avatar answered Feb 19 '26 15:02

Amit Bhati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!