Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - How to specify a single implementation for interface-referenced deserialization?

I want to deserialize a JSON-Object with Jackson. Because the target is an interface I need to specify which implementation should be used.

This information could be stored in the JSON-Object, using @JsonTypeInfo-Annotation. But I want to specify the implementation in source code because it's always the same.

Is this possible?

like image 420
Max Schmidt Avatar asked Oct 02 '12 10:10

Max Schmidt


People also ask

How does Jackson deserialize dates from JSON?

How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.

How does Jackson Deserialization work?

Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.

How does ObjectMapper readValue work?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

Use a SimpleAbstractTypeResolver:

ObjectMapper mapper = new ObjectMapper();  SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion());  SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver(); resolver.addMapping(Interface.class, Implementation.class);  module.setAbstractTypes(resolver);  mapper.registerModule(module); 
like image 186
David Grant Avatar answered Oct 06 '22 15:10

David Grant