BAEL-6749 improve examples for handling null fields with Jackson

This commit is contained in:
Sam Gardner 2023-07-17 15:41:07 +01:00
parent a4d39d14dd
commit 2fec1f1f7e
2 changed files with 3 additions and 6 deletions

View File

@ -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";

View File

@ -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");
} }