Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Jackson to throw an exception when a field is missing

Tags:

jackson

I have a class like this:

public class Person {   private String name;   public String getName(){     return name;   } } 

I am using an ObjectMapper configured like this:

ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

I have a String str that contains this { "address" : "something" }. Note that there is no "name" field in the json. If I do something like this:

mapper.readValue(str, Person.class); 

then I actually get back a Person object with name set to null. Is there a way to configure the mapper to throw an exception instead, or return a null reference instead of a Person? I want Jackson to consider missing fields a failure and don't want to do explicit null checks on the resulting object's fields.

like image 600
mushroom Avatar asked Feb 05 '15 23:02

mushroom


People also ask

How do you tell Jackson to ignore a field during serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

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.

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.

Is ObjectMapper Jackson thread safe?

Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.


1 Answers

As of Jackson 2.6, there is a way, but it does not work on class attribute annotations, only constructor annotations:

/* DOES *NOT* THROW IF bar MISSING */ public class Foo {         @JsonProperty(value = "bar", required = true)     public int bar; }  /* DOES THROW IF bar MISSING */ public class Foo {     public int bar;     @JsonCreator     public Foo(@JsonProperty(value = "bar", required = true) int bar) {         this.bar = bar;     } } 
like image 85
zopieux Avatar answered Sep 22 '22 02:09

zopieux