Jackson Yaml 类型信息在序列化时出错 [英] Jackson Yaml Type Info is wrong on serialization

查看:31
本文介绍了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 类型信息在序列化时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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