40

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?

Ben Barkay
  • 5,473
  • 2
  • 20
  • 29
Max Schmidt
  • 7,377
  • 5
  • 23
  • 29
  • The question here is about a single implementation, but one could research about inheritance in general, and we should then see the @JsonTypeInfo annotation. example https://stackoverflow.com/questions/28089484/deserialization-with-jsonsubtypes-for-no-value-missing-property-error/31016173#31016173 – pdem Dec 21 '17 at 15:34

3 Answers3

48

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);
Mr00Anderson
  • 854
  • 8
  • 16
David Grant
  • 13,929
  • 3
  • 57
  • 63
35

There is another approach that will work if you have just single interface implementation.

public class ClassYouWantToDeserialize {
    @JsonDeserialize(as = ImplementationClass.class)
    private InterfaceClass property;
...
}

This question was answered a while ago but I want to give you another option that doesn't require to tune ObjectMapper and also much simpler then @JsonTypeInfo annotation.

Ilya Ovesnov
  • 4,079
  • 1
  • 27
  • 31
9

You can use @JsonDeserialize(as = ImplementationClass.class) on the interface as well and all references will be deserialized the same way.

Note, if one of your Implementation classes is an enum, you might need @JsonFormat(shape = JsonFormat.Shape.OBJECT) on the enum as well.

Jason Smiley
  • 151
  • 2
  • 3