BAEL-6749 improve examples for handling null fields with Jackson
This commit is contained in:
parent
a4d39d14dd
commit
2fec1f1f7e
|
@ -1,13 +1,10 @@
|
||||||
package com.baeldung.jackson.defaultvalues;
|
package com.baeldung.jackson.defaultvalues;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
public class SetterDefaultValue {
|
||||||
|
|
||||||
public class JsonSetterDefaultValue {
|
|
||||||
|
|
||||||
private String required;
|
private String required;
|
||||||
private String optional = "valueIfMissingEntirely";
|
private String optional = "valueIfMissingEntirely";
|
||||||
|
|
||||||
@JsonSetter("optional")
|
|
||||||
public void setOptional(String optional){
|
public void setOptional(String optional){
|
||||||
if(optional == null){
|
if(optional == null){
|
||||||
this.optional = "valueIfNull";
|
this.optional = "valueIfNull";
|
|
@ -17,10 +17,10 @@ public class DefaultValuesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAClassWithAJsonSetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException {
|
public void givenAClassWithASetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException {
|
||||||
String nullOptionalField = "{\"required\": \"value\", \"optional\": null}";
|
String nullOptionalField = "{\"required\": \"value\", \"optional\": null}";
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
JsonSetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, JsonSetterDefaultValue.class);
|
SetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, SetterDefaultValue.class);
|
||||||
assert(createdObject.getRequired()).equals("value");
|
assert(createdObject.getRequired()).equals("value");
|
||||||
assert(createdObject.getOptional()).equals("valueIfNull");
|
assert(createdObject.getOptional()).equals("valueIfNull");
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue