Search in sources :

Example 1 with InvalidTypeIdException

use of com.fasterxml.jackson.databind.exc.InvalidTypeIdException in project jackson-databind by FasterXML.

the class TestSubtypes method testDefaultImplViaModule.

// [JACKSON-505]: ok to also default to mapping there might be for base type
public void testDefaultImplViaModule() throws Exception {
    final String JSON = "{\"a\":123}";
    // first: without registration etc, epic fail:
    try {
        MAPPER.readValue(JSON, SuperTypeWithoutDefault.class);
        fail("Expected an exception");
    } catch (InvalidTypeIdException e) {
        verifyException(e, "missing type id property '#type'");
    }
    // but then succeed when we register default impl
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("test", Version.unknownVersion());
    module.addAbstractTypeMapping(SuperTypeWithoutDefault.class, DefaultImpl505.class);
    mapper.registerModule(module);
    SuperTypeWithoutDefault bean = mapper.readValue(JSON, SuperTypeWithoutDefault.class);
    assertNotNull(bean);
    assertEquals(DefaultImpl505.class, bean.getClass());
    assertEquals(123, ((DefaultImpl505) bean).a);
    bean = mapper.readValue("{\"#type\":\"foobar\"}", SuperTypeWithoutDefault.class);
    assertEquals(DefaultImpl505.class, bean.getClass());
    assertEquals(0, ((DefaultImpl505) bean).a);
}
Also used : InvalidTypeIdException(com.fasterxml.jackson.databind.exc.InvalidTypeIdException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule)

Aggregations

ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 InvalidTypeIdException (com.fasterxml.jackson.databind.exc.InvalidTypeIdException)1 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)1