Jackson - 如何为接口引用的反序列化指定单个实现? [英] Jackson - How to specify a single implementation for interface-referenced deserialization?

查看:20
本文介绍了Jackson - 如何为接口引用的反序列化指定单个实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Jackson 反序列化一个 JSON 对象.因为目标是一个接口,所以我需要指定应该使用哪个实现.

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

此信息可以使用@JsonTypeInfo-Annotation 存储在 JSON-Object 中.但我想在源代码中指定实现,因为它总是相同的.

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.

这可能吗?

推荐答案

使用 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);

这篇关于Jackson - 如何为接口引用的反序列化指定单个实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆