18
18
import com .fasterxml .jackson .annotation .JsonIgnore ;
19
19
import com .fasterxml .jackson .databind .JsonNode ;
20
20
import com .fasterxml .jackson .databind .ObjectMapper ;
21
+ import com .fasterxml .jackson .databind .node .NullNode ;
22
+ import com .fasterxml .jackson .databind .node .ObjectNode ;
21
23
import org .junit .Test ;
22
24
import org .skr .common .util .JsonUtil ;
23
25
import org .skr .config .json .JsonSkipPersistence ;
24
26
27
+ import java .util .Optional ;
28
+
25
29
import static org .hamcrest .MatcherAssert .assertThat ;
26
30
import static org .hamcrest .Matchers .*;
27
31
@@ -57,6 +61,12 @@ public record B(
57
61
@ JsonSkipPersistence
58
62
int b ) {}
59
63
64
+ public static class C {
65
+ public Optional <Integer > a = Optional .empty ();
66
+
67
+ public Optional <Integer > b ;
68
+ }
69
+
60
70
@ Test
61
71
public void testSkipPersistence () {
62
72
ObjectMapper objectMapper = JsonUtil .setupPersistentObjectMapper (JsonUtil .getObjectMapper ());
@@ -78,4 +88,29 @@ public void testSkipPersistence() {
78
88
assertThat (json .get ("a" ), notNullValue ());
79
89
assertThat (json .get ("b" ), nullValue ());
80
90
}
91
+
92
+ @ Test
93
+ public void testOptional () {
94
+ ObjectMapper objectMapper = JsonUtil .setupPersistentObjectMapper (JsonUtil .getObjectMapper ());
95
+
96
+ C c1 = new C ();
97
+ c1 .a = Optional .of (1 );
98
+ JsonNode json = JsonUtil .toJsonNode (objectMapper , c1 );
99
+ assertThat (json .get ("a" ), notNullValue ());
100
+ assertThat (json .get ("a" ).asInt (), equalTo (1 ));
101
+
102
+ C c2 = new C ();
103
+ json = JsonUtil .toJsonNode (objectMapper , c2 );
104
+ assertThat (json .get ("a" ), equalTo (NullNode .getInstance ()));
105
+ assertThat (json .get ("b" ), nullValue ());
106
+
107
+ C c3 = objectMapper .convertValue (json , C .class );
108
+ assertThat (c3 .a , equalTo (Optional .empty ()));
109
+ assertThat (c3 .b , nullValue ());
110
+
111
+ ObjectNode c4Json = objectMapper .createObjectNode ();
112
+ C c4 = objectMapper .convertValue (c4Json .put ("a" , "1" ), C .class );
113
+ assertThat (c4 .a , notNullValue ());
114
+ assertThat (c4 .a .get (), equalTo (1 ));
115
+ }
81
116
}
0 commit comments