Skip to content

Commit ed08cc4

Browse files
committed
Add an Optional convenience method.
1 parent 14dc403 commit ed08cc4

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

com.io7m.dixmont.core/src/main/java/com/io7m/dixmont/core/DmJsonRestrictedDeserializerBuilderType.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.util.List;
2222
import java.util.Map;
2323
import java.util.Objects;
24+
import java.util.Optional;
2425
import java.util.Set;
2526

2627
/**
@@ -88,6 +89,28 @@ default DmJsonRestrictedDeserializerBuilderType allowClasses(
8889
return this;
8990
}
9091

92+
/**
93+
* Allow access to optionals of the given class.
94+
*
95+
* @param clazz The class
96+
*
97+
* @return this
98+
*
99+
* @since 3.0.0
100+
*/
101+
102+
default DmJsonRestrictedDeserializerBuilderType allowOptionalOfClass(
103+
final Class<?> clazz)
104+
{
105+
return this.allowClass(clazz)
106+
.allowClassName(
107+
"%s<%s>".formatted(
108+
Optional.class.getCanonicalName(),
109+
clazz.getCanonicalName()
110+
)
111+
);
112+
}
113+
91114
/**
92115
* Allow access to lists of the given class.
93116
*

com.io7m.dixmont.tests/src/main/java/com/io7m/dixmont/tests/DmJsonRestrictedDeserializersTest.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import java.util.List;
2828
import java.util.Map;
29+
import java.util.Optional;
2930
import java.util.Set;
3031

3132
import static com.io7m.dixmont.tests.EnumExample.ENUM_EXAMPLE_A;
@@ -257,6 +258,34 @@ public void testListIntAllowedConvenience()
257258
);
258259
}
259260

261+
@Test
262+
public void testOptionalIntAllowedConvenience()
263+
throws Exception
264+
{
265+
final var deserializers =
266+
DmJsonRestrictedDeserializers.builder()
267+
.allowOptionalOfClass(Integer.class)
268+
.build();
269+
270+
final var simpleModule = new SimpleModule();
271+
simpleModule.setDeserializers(deserializers);
272+
273+
final var builder = JsonMapper.builder();
274+
builder.addModule(simpleModule);
275+
276+
final var mapper =
277+
(ObjectMapper) builder.disable(FAIL_ON_UNKNOWN_PROPERTIES)
278+
.build();
279+
280+
assertEquals(
281+
Optional.of(Integer.valueOf(23)),
282+
mapper.readValue(
283+
"23", new TypeReference<Optional<Integer>>()
284+
{
285+
})
286+
);
287+
}
288+
260289
@Test
261290
public void testMultiConvenience()
262291
throws Exception

0 commit comments

Comments
 (0)