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

前端 未结 3 682
感动是毒
感动是毒 2020-12-05 09: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

相关标签:
3条回答
  • 2020-12-05 10:04

    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.

    0 讨论(0)
  • 2020-12-05 10:11

    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.

    0 讨论(0)
  • 2020-12-05 10:29

    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);
    
    0 讨论(0)
提交回复
热议问题