Jackson Yaml Type Info is wrong on serialization(Jackson Yaml 类型信息在序列化时出错)
问题描述
通过 Jackson 将对象序列化为 yml 时,我得到以下输出:
I am getting the following output when serializing an object to yml via Jackson:
---
commands:
dev: !<foo.bar.baz.DevCommand>
但是,我想要的是:
---
commands:
dev:
type: foo.bar.baz.DevCommand
我能够很好地反序列化.也就是说,反序列化部分按预期工作.我在我能想到的任何地方都放了以下注释:
I am able to deserialize that fine. That is to say, the deserialization part works as intended. I have put the following annotation everywhere I can think of:
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")
包括 DevCommand 接口、DevCommand 上的具体类、具有 commands 映射的类型(字段和 getter/setter).
Including on the DevCommand interface, on DevCommand the concrete class, on the type which has the commands map (both the field and the getters/setters).
我需要做什么来强制 Jackson 使用我想要的类型格式?
What do I need to do to force Jackson to use the type format I want?
推荐答案
Yaml 已经内置了类型信息,所以 Jackson 默认使用它.从 this issue,修复是禁用使用本机类型 ID.
Yaml has type information built in already, so Jackson uses that by default. From this issue, the fix is to disable using the native type id.
YAML 具有原生类型 ID 和对象 ID,因此默认使用它们(假设这是用户喜欢的).但是您可以通过以下方式禁用它:
YAML has native Type Ids and Object Ids, so by default those are used (assuming this is what users prefer). But you can disable this with:
YAMLGenerator.Feature.USE_NATIVE_TYPE_ID
并专门禁用它;类似:
YAMLFactory f = new YAMLFactory();
f.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);
ObjectMapper m = new ObjectMapper(f);
或者,为了方便
YAMLMapper m = new YAMLMapper()
disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);
这篇关于Jackson Yaml 类型信息在序列化时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jackson Yaml 类型信息在序列化时出错
基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
