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.
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.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property.
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.
Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With