Jackson Yaml 类型信息在序列化时出错

Jackson Yaml Type Info is wrong on serialization(Jackson Yaml 类型信息在序列化时出错)
本文介绍了Jackson Yaml 类型信息在序列化时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)