java - 没有Jackson实现类的接口类型的POJO反序列化属性
问题描述
我在将 json 反序列化为 POJO 类时遇到问题,如下所示:
@Data
public class Foo {
private String fieldA;
private String fieldB;
private IBar fieldC;
}
IBar
是一个为某些类定义 getter 的接口。我发现的解决方案之一是使用@JsonDeserialize(as = BarImpl.class)
where BarImpl
will implement IBar
interface。问题是实现该接口的类(例如BarImpl
)位于另一个 maven 模块中,我无法从当前模块访问,因此我无法在该注释中使用其中一个 impl 类。你能告诉我是否有其他解决方案吗?
谢谢你的建议。
解决方案
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);
推荐阅读
- python - SQLAlchemy 仅查找包含特定子代的父代
- javascript - 用另一个对象更新对象数组中的对象
- azure-machine-learning-service - 并非运行配置中指定的所有数据存储(workspaceblobstore)都存在
- c# - 反序列化 XML 中的嵌套集合
- selenium - 在 SeleniumIDE 中禁用鼠标悬停、鼠标悬停和其他
- angular - 如何使用从以前的离子选择中选择的数组动态填充离子选择
- java - Java httpClient 流式请求
- r - str_match_all 带换行符?
- mongodb - MongoDB 统计非缺失字段的数量
- flutter - 如何将修改后的插件添加到我的应用程序?如何给路径?