|
| 1 | +package com.fasterxml.jackson.databind.jsontype; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonSubTypes; |
| 4 | +import com.fasterxml.jackson.annotation.JsonTypeInfo; |
| 5 | + |
| 6 | +import com.fasterxml.jackson.databind.*; |
| 7 | + |
| 8 | +public class PolymorphicDeserErrorHandlingTest extends BaseMapTest |
| 9 | +{ |
| 10 | + @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, |
| 11 | + property = "clazz") |
| 12 | + abstract static class BaseForUnknownClass { |
| 13 | + } |
| 14 | + |
| 15 | + static class BaseUnknownWrapper { |
| 16 | + public BaseForUnknownClass value; |
| 17 | + } |
| 18 | + |
| 19 | + // [databind#2668] |
| 20 | + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") |
| 21 | + @JsonSubTypes({ |
| 22 | + @JsonSubTypes.Type(value = Child1.class, name = "child1"), |
| 23 | + @JsonSubTypes.Type(value = Child2.class, name = "child2") |
| 24 | + }) |
| 25 | + static class Parent2668 { |
| 26 | + } |
| 27 | + |
| 28 | + static class Child1 extends Parent2668 { |
| 29 | + public String bar; |
| 30 | + } |
| 31 | + |
| 32 | + static class Child2 extends Parent2668 { |
| 33 | + public String baz; |
| 34 | + } |
| 35 | + |
| 36 | + /* |
| 37 | + /********************************************************************** |
| 38 | + /* Test methods |
| 39 | + /********************************************************************** |
| 40 | + */ |
| 41 | + |
| 42 | + private final ObjectMapper MAPPER = newJsonMapper(); |
| 43 | + |
| 44 | + public void testUnknownClassAsSubtype() throws Exception |
| 45 | + { |
| 46 | + ObjectReader reader = MAPPER.readerFor(BaseUnknownWrapper.class) |
| 47 | + .without(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); |
| 48 | + BaseUnknownWrapper w = reader.readValue(aposToQuotes |
| 49 | + ("{'value':{'clazz':'com.foobar.Nothing'}}'")); |
| 50 | + assertNotNull(w); |
| 51 | + } |
| 52 | + |
| 53 | + // [databind#2668] |
| 54 | + public void testSubType2668() throws Exception |
| 55 | + { |
| 56 | + String json = "{\"type\": \"child2\", \"baz\":\"1\"}"; // JSON for Child2 |
| 57 | + |
| 58 | + try { |
| 59 | + /*Child1 c =*/ MAPPER.readValue(json, Child1.class); // Deserializing into Child1 |
| 60 | + fail("Should not pass"); |
| 61 | + } catch (JsonMappingException e) { |
| 62 | + verifyException(e, "not subtype of"); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments