Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson ObjectMapper: specify required fields [duplicate]

I'm using Jackson's readValue() method on an object mapper to read from a JSON file and convert it into my java object.

eg.

mapperObject.readValue( node, MyTargetClass.class )

Are there any annotations that I can set on MyTargetClass to enforce required attributes? For example, if I have a JSON object with properties ABC,DEF and GHI, and my Json is the following

{
  "ABC" : "somevalue"
  "DEF" : "someothervalue" 
}

I want it to fail somehow, and only succeed on the readValue if it contained ABC, DEF and GHI.

like image 813
Ren Avatar asked Sep 08 '26 02:09

Ren


2 Answers

You can mark a property as required with the @JsonProperty(required = true) annotation, and it will throw a JsonMappingException during deserialization if the property is missing or null.

like image 170
postfuturist Avatar answered Sep 10 '26 17:09

postfuturist


Jackson does not include validation functionality, and this is by design (i.e. that is considered out-of-scope). But what is usually used is Bean Validation API implementation. The nice thing about this is decoupling between data format handling, and validation logic. This is what frameworks like DropWizard use; and it's the direction JAX-RS (like Jersey) are taking things for JAX-RS 2.0.

like image 37
StaxMan Avatar answered Sep 10 '26 16:09

StaxMan



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!