首页 > 解决方案 > 没有Jackson实现类的接口类型的POJO反序列化属性

问题描述

我在将 json 反序列化为 POJO 类时遇到问题,如下所示:

@Data
public class Foo {
   private String fieldA;
   private String fieldB;
   private IBar fieldC; 
}

IBar是一个为某些类定义 getter 的接口。我发现的解决方案之一是使用@JsonDeserialize(as = BarImpl.class)where BarImplwill implement IBarinterface。问题是实现该接口的类(例如BarImpl)位于另一个 maven 模块中,我无法从当前模块访问,因此我无法在该注释中使用其中一个 impl 类。你能告诉我是否有其他解决方案吗?

谢谢你的建议。

标签: javajackson

解决方案


Are you sure you mean deserialization? You'll need a concrete implementation of your interface if Jackson's going to be able to create Java objects for you.

  • deserialization = Json String -> Java object
  • serialization = Java object -> Json String

When serializing Jackson will use the runtime class of the object, so it will use the actual implementations rather than attempt to use the interface. If you want to customize this you can add a serializer for your interface. You'll need to decide exactly what you want to write out.

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(IBar.class, new JsonSerializer<IBar>() {

            @Override
            public void serialize(IBar value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeStartObject();
                gen.writeStringField("fieldName", value.getFieldName());
                gen.writeEndObject();
            }


        });
        objectMapper.registerModule(module);

推荐阅读