File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
jackson-modules/jackson-core/src
main/java/com/baeldung/jackson/defaultvalues
test/java/com/baeldung/jackson/defaultvalues Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .baeldung .jackson .defaultvalues ;
2
+
3
+ public class SetterDefaultValueAsEmptyString {
4
+
5
+ private String required ;
6
+ private String optional = "valueIfMissingEntirely" ;
7
+
8
+ public void setOptional (String optional ){
9
+ if (optional == null ){
10
+ this .optional = "" ;
11
+ }
12
+ }
13
+
14
+ public String getRequired () {
15
+ return required ;
16
+ }
17
+
18
+ public String getOptional () {
19
+ return optional ;
20
+ }
21
+
22
+ @ Override
23
+ public String toString () {
24
+ return "NonAnnotatedDefaultValue{" + "required='" + required + '\'' + ", optional='" + optional + '\'' + '}' ;
25
+ }
26
+
27
+ }
Original file line number Diff line number Diff line change @@ -25,6 +25,15 @@ public void givenAClassWithASetter_whenReadingJsonWithNullOptionalValue_thenExpe
25
25
assert (createdObject .getOptional ()).equals ("valueIfNull" );
26
26
}
27
27
28
+ @ Test
29
+ public void givenAClassWithASetter_whenReadingJsonWithNullOptionalValue_thenEmptyStringInResult () throws JsonProcessingException {
30
+ String nullOptionalField = "{\" required\" : \" value\" , \" optional\" : null}" ;
31
+ ObjectMapper objectMapper = new ObjectMapper ();
32
+ SetterDefaultValueAsEmptyString createdObject = objectMapper .readValue (nullOptionalField , SetterDefaultValueAsEmptyString .class );
33
+ assert (createdObject .getRequired ()).equals ("value" );
34
+ assert (createdObject .getOptional ()).equals ("" );
35
+ }
36
+
28
37
@ Test
29
38
public void givenAClassWithAJsonSetterNullsSkip_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult () throws JsonProcessingException {
30
39
String nullOptionalField = "{\" required\" : \" value\" , \" optional\" : null}" ;
You can’t perform that action at this time.
0 commit comments