|
| 1 | +package com.fasterxml.jackson.datatype.jdk8; |
| 2 | + |
| 3 | +import java.util.Optional; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 6 | +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; |
| 7 | +import com.fasterxml.jackson.databind.annotation.JsonSerialize; |
| 8 | +import com.fasterxml.jackson.databind.util.StdConverter; |
| 9 | + |
| 10 | +// [modules-java#294]: Optional + converters |
| 11 | +public class OptionalConverterTest extends ModuleTestBase |
| 12 | +{ |
| 13 | + static class Point |
| 14 | + { |
| 15 | + public int x, y; |
| 16 | + |
| 17 | + protected Point() { } |
| 18 | + public Point(int v1, int v2) { |
| 19 | + x = v1; |
| 20 | + y = v2; |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + static class PointDeserConverter extends StdConverter<int[], Point> |
| 25 | + { |
| 26 | + @Override |
| 27 | + public Point convert(int[] value) { |
| 28 | + return new Point(value[0], value[1]); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + static class PointSerConverter extends StdConverter<Point, int[]> |
| 33 | + { |
| 34 | + @Override public int[] convert(Point value) { |
| 35 | + return new int[] { value.x, value.y }; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + static class PointReferenceBean { |
| 40 | + @JsonDeserialize(contentConverter=PointDeserConverter.class) |
| 41 | + @JsonSerialize(contentConverter=PointSerConverter.class) |
| 42 | + public Optional<Point> opt; |
| 43 | + |
| 44 | + protected PointReferenceBean() { } |
| 45 | + public PointReferenceBean(int x, int y) { |
| 46 | + opt = Optional.of(new Point(x, y)); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /* |
| 51 | + /********************************************************** |
| 52 | + /* Test methods |
| 53 | + /********************************************************** |
| 54 | + */ |
| 55 | + |
| 56 | + private final ObjectMapper MAPPER = mapperWithModule(); |
| 57 | + |
| 58 | + // [modules-java#294]: Optional + converters, deser |
| 59 | + public void testDeserializeOptionalConverting() throws Exception { |
| 60 | + PointReferenceBean w = MAPPER.readerFor(PointReferenceBean.class) |
| 61 | + .readValue("{\"opt\": [1,2]}"); |
| 62 | + assertNotNull(w); |
| 63 | + assertNotNull(w.opt); |
| 64 | + Point p = w.opt.get(); |
| 65 | + assertNotNull(p); |
| 66 | + assertEquals(1, p.x); |
| 67 | + assertEquals(2, p.y); |
| 68 | + } |
| 69 | + |
| 70 | + // [modules-java#294]: Optional + converters, ser |
| 71 | + public void testSerializeOptionalConverting() throws Exception { |
| 72 | + assertEquals("{\"opt\":[3,4]}", |
| 73 | + MAPPER.writeValueAsString(new PointReferenceBean(3, 4))); |
| 74 | + } |
| 75 | +} |
0 commit comments