Jackson完全忽略了Jaxb XML相关的注解

huangapple go评论90阅读模式
英文:

Jackson completely ignore Jaxb XML related annotations

问题

想象一种情况,当你有一个Java模型时,你需要将它序列化成XML和CSV格式。

我使用Jaxb Marshaller来处理XML,使用Jackson的CsvMapperObjectMapper)来处理CSV。

由于这两种格式略有不同,我希望Jackson的CsvMapper能忽略掉与Jaxb相关的注解,比如@XmlType@XmlElement。因为Jackson会考虑XML注解,这会导致错误的结果。

我该如何做到这一点?

英文:

Imagine a situation when you have a model in Java, and you have to serialize it both to XML and CSV.

I am using Jaxb Marshaller for XML and Jackson's CsvMapper (ObjectMapper) for CSV.

Since the formats are slightly different, I want Jackson's CsvMapper to ignore Jaxb related annotations like @XmlType or @XmlElement. Because Jackson is getting information/considers xml annotations as well and it leads to wrong result.

How can I do it?

答案1

得分: 1

这是您可能创建新的 CsvMapper 的方式:

CsvMapper csvMapper = new CsvMapper();
csvMapper.findAndRegisterModules();

findAndRegisterModules 方法会调用 findModules 方法,其文档说明如下:

> 通过 JDK 的 ServiceLoader 工具定位可用的模块,以及模块提供的 SPI。

所以,很可能您的类路径上有 jackson-module-jaxb-annotations 模块,这就是为什么 CsvMapper 可以识别 JAXB 注解。

要解决这个问题,您需要删除对 findAndRegisterModules 方法的调用,并且仅注册您所需的那些模块。

英文:

This is the way how you probably create new CsvMapper:

CsvMapper csvMapper = new CsvMapper();
csvMapper.findAndRegisterModules();

findAndRegisterModules method invokes findModules which documentation says:

> Method for locating available methods, using JDK ServiceLoader facility, along with module-provided SPI.

So, probably you have jackson-module-jaxb-annotations module on class path and this is why CsvMapper recognizes JAXB annotations.

To fix it, you need to remove invocation of this method findAndRegisterModules and register only these modules you needed.

huangapple
  • 本文由 发表于 2020年8月20日 19:29:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63504075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定