|
| 1 | +package com.fasterxml.jackson.databind.tofix; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +import com.fasterxml.jackson.core.*; |
| 8 | + |
| 9 | +import com.fasterxml.jackson.databind.*; |
| 10 | +import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; |
| 11 | +import com.fasterxml.jackson.databind.json.JsonMapper; |
| 12 | +import com.fasterxml.jackson.databind.testutil.DatabindTestUtil; |
| 13 | +import com.fasterxml.jackson.databind.testutil.failure.JacksonTestFailureExpected; |
| 14 | + |
| 15 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 16 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 17 | + |
| 18 | +public class DeserializationProblemHandler4656Test extends DatabindTestUtil |
| 19 | +{ |
| 20 | + // For [databind#4656] |
| 21 | + static class Person4656 { |
| 22 | + public String id; |
| 23 | + public String name; |
| 24 | + public Long age; |
| 25 | + } |
| 26 | + |
| 27 | + static class ProblemHandler4656 extends DeserializationProblemHandler |
| 28 | + { |
| 29 | + protected static final String NUMBER_LONG_KEY = "$numberLong"; |
| 30 | + |
| 31 | + @Override |
| 32 | + public Object handleUnexpectedToken(DeserializationContext ctxt, JavaType targetType, |
| 33 | + JsonToken t, JsonParser p, String failureMsg) throws IOException |
| 34 | + { |
| 35 | + if (targetType.getRawClass().equals(Long.class) && t == JsonToken.START_OBJECT) { |
| 36 | + JsonNode tree = p.readValueAsTree(); |
| 37 | + if (tree.get(NUMBER_LONG_KEY) != null) { |
| 38 | + try { |
| 39 | + return Long.parseLong(tree.get(NUMBER_LONG_KEY).asText()); |
| 40 | + } catch (NumberFormatException e) { } |
| 41 | + } |
| 42 | + } |
| 43 | + return NOT_HANDLED; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // For [databind#4656] |
| 48 | + @JacksonTestFailureExpected |
| 49 | + @Test |
| 50 | + public void testIssue4656() throws Exception { |
| 51 | + ObjectMapper mapper = JsonMapper.builder() |
| 52 | + .addHandler(new ProblemHandler4656()) |
| 53 | + .build(); |
| 54 | + final String json = "{\"id\": \"12ab\", \"name\": \"Bob\", \"age\": {\"$numberLong\": \"10\"}}"; |
| 55 | + Person4656 person = mapper.readValue(json, Person4656.class); |
| 56 | + assertNotNull(person); |
| 57 | + assertEquals("12ab", person.id); |
| 58 | + assertEquals("Bob", person.name); |
| 59 | + assertEquals(10L, person.age); |
| 60 | + } |
| 61 | +} |
0 commit comments