Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Required property?

Tags:

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 820
Ren Avatar asked Dec 07 '12 03:12

Ren


People also ask

How do I make a JSON property mandatory?

If you want to make sure a json field is provided, you have to use the @JsonProperty(value = "fieldName", required = true) annotation as a parameter to the constructor.

What is JsonProperty annotation?

The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.

Is @JsonProperty required?

You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using.

How do I ignore JsonProperty?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.


1 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.

Edit: I received a downvote for this without comment. I'd love to know why, since it does exactly the right thing.

like image 164
postfuturist Avatar answered Oct 18 '22 23:10

postfuturist