|
1 | 1 | package com.fasterxml.jackson.jr.ob.impl;
|
2 | 2 |
|
3 | 3 | import java.io.IOException;
|
| 4 | +import java.util.Map; |
4 | 5 |
|
5 | 6 | import com.fasterxml.jackson.core.JsonParser;
|
6 | 7 | import com.fasterxml.jackson.jr.ob.JSON;
|
@@ -110,6 +111,36 @@ public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
|
110 | 111 | }
|
111 | 112 | }
|
112 | 113 |
|
| 114 | + static class Point { |
| 115 | + public int _x, _y; |
| 116 | + |
| 117 | + public Point(int x, int y) { |
| 118 | + _x = x; |
| 119 | + _y = y; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + static class PointReader extends ValueReader { |
| 124 | + public PointReader() { super(Point.class); } |
| 125 | + |
| 126 | + @Override |
| 127 | + public Object read(JSONReader reader, JsonParser p) throws IOException { |
| 128 | + Map<Object, Object> map = reader.readMap(); |
| 129 | + return new Point((Integer) map.get("x"), (Integer) map.get("y")); |
| 130 | + } |
| 131 | + |
| 132 | + } |
| 133 | + |
| 134 | + static class PointReaderProvider extends ReaderWriterProvider { |
| 135 | + @Override |
| 136 | + public ValueReader findValueReader(JSONReader readContext, Class<?> type) { |
| 137 | + if (type == Point.class) { |
| 138 | + return new PointReader(); |
| 139 | + } |
| 140 | + return null; |
| 141 | + } |
| 142 | + } |
| 143 | + |
113 | 144 | /*
|
114 | 145 | /**********************************************************************
|
115 | 146 | /* Test methdods
|
@@ -178,4 +209,25 @@ public void testCustomStringReader() throws Exception
|
178 | 209 | .beanFrom(String.class, quote("Some text"));
|
179 | 210 | assertEquals("SOME TEXT", allCaps);
|
180 | 211 | }
|
| 212 | + |
| 213 | + // But also can use methods from "JSONReader" for convenience |
| 214 | + public void testCustomDelegatingReader() throws Exception |
| 215 | + { |
| 216 | + // First: without handler, will fail to map |
| 217 | + final String doc = "{\"y\" : 3, \"x\": 2 }"; |
| 218 | + try { |
| 219 | + JSON.std.beanFrom(Point.class, doc); |
| 220 | + fail("Should not pass"); |
| 221 | + } catch (JSONObjectException e) { |
| 222 | + verifyException(e, "$Point"); |
| 223 | + verifyException(e, "constructor to use"); |
| 224 | + } |
| 225 | + |
| 226 | + // then with custom, should be fine |
| 227 | + JSON json = JSON.std |
| 228 | + .with(new PointReaderProvider()); |
| 229 | + Point v = json.beanFrom(Point.class, doc); |
| 230 | + assertEquals(2, v._x); |
| 231 | + assertEquals(3, v._y); |
| 232 | + } |
181 | 233 | }
|
0 commit comments