问题描述
我发现了很棒的Jackson XML库:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.10</version>
<type>bundle</type>
</dependency>
它无需额外配置即可工作:
val xmlMapper = XmlMapper()
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
xmlMapper.writeValueAsstring(CustomIntegration)
其中CustomIntegration
是数据类
data class CustomIntegration(val name: String)
对于输入 CustomeIntegration("Integration A")
,输出将是
<CustomIntegration>
<name>
Integrartion A
</name>
</CustomIntegration>
问题是在反序列化为XML时如何将CustomIntegration
更改为integration
?我想解决一些用例:
- 任何类的单一实现,因此
CoolIntegration
,AwesomeIntegration
都将转换为标签integration
- 我不能仅仅将类
CustomIntegration
重命名为integration
,因为它与SOAP集成中的SOAP:envelope
几乎一样,因此在同一标签中可以包含不同的内容 - 理想情况下,我想编写尽可能少的代码,以简化维护工作
到目前为止,我发现的唯一解决方案是编写自定义解串器,但这并不能完全解决我要满足的所有非功能性要求。
解决方法
我在another SO post中找到的解决方案。
要更改XML中的根元素名称,您需要添加@JsonRootName(value = "integration")
批注。
@JsonRootName(value = "integration")
data class CustomIntegration(val name: String)
输出为:
<integration>
<name>
Integrartion A
</name>
</integration>