I have class
@Data
class Person {
@JsonProperty(value="name", defaultValue = "null")
private String name = "null";
@JsonProperty(value="surName", defaultValue = "null")
private String surName= "null";
}
When I try to deserialize string like {"name":null, "surName":null} with
new ObjectMapper().readValue(json, Person.class);
I got Object with null fields, but I need with "null" fields. How to make that?
The property defaultValue
of the @JsonProperty annotation does not lead to actual setting the default value and only used for informational purposes. That may be misleading but it is how currently Jackson is implemented: https://fasterxml.github.io/jackson-annotations/javadoc/2.14/com/fasterxml/jackson/annotation/JsonProperty.html#defaultValue--
Setting default value for Java fields probably won't work either since you have actually these properties in your JSON so the setters will be actually called and will overwrite the original "null" values (you can check that with debugger).
A simple solution would be to set @JsonSetter(nulls = Nulls.SKIP)
:
The working example:
@Data
public class Person {
@JsonProperty
@JsonSetter(nulls = Nulls.SKIP)
private String name = "null";
@JsonProperty
@JsonSetter(nulls = Nulls.SKIP)
private String surName = "null";
}
public class PersonTest {
@Test
public void testDeserializePerson() throws JsonProcessingException {
var result = new ObjectMapper().readValue("{\"name\":null, \"surName\":null}", Person.class);
assertEquals(result.getName(), "null");
assertEquals(result.getSurName(), "null");
}
}