我有一些 XML 格式的简单数据,我需要将其转换为 JSON,并且还能够将 JSON 转换回相同的 XML 字符串。但是我在使用现有的杰克逊(2.0.6 版)库时遇到了问题。
这是具有类似结构的 XML 数据示例
<channels>
<channel>A</channel>
<channel>B</channel>
<channel>C</channel>
</channels>
为了能够将其转换回原始 XML,我希望 JSON 看起来像这样
{
"channels": {
"channel": [
"A",
"B",
"C"
]
}
}
然而杰克逊给了我
{"channel":"C"}
不保留根元素名称,而是创建通道数组,最后一个覆盖以前的。
查看 com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer 的源代码,我发现该库不支持这一点,但允许覆盖和更改行为。
/**
* Method called when there is a duplicate value for a field.
* By default we don't care, and the last value is used.
* Can be overridden to provide alternate handling, such as throwing
* an exception, or choosing different strategy for combining values
* or choosing which one to keep.
*
* @param fieldName Name of the field for which duplicate value was found
* @param objectNode Object node that contains values
* @param oldValue Value that existed for the object node before newValue
* was added
* @param newValue Newly added value just added to the object node
*/
protected void _handleDuplicateField(String fieldName, ObjectNode objectNode,
JsonNode oldValue, JsonNode newValue)
throws JsonProcessingException
{
// By default, we don't do anything
;
}
所以我的问题是
- 有没有人编写自定义反序列化器来支持此功能?或者有另一种方法可以解决这个问题。
- 如何保留根元素名称?
下面是一个测试示例
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class Test {
public static void main(String[] args) throws Exception {
String xml="<channels><channel>A</channel><channel>B</channel><channel>C</channel></channels>";
XmlMapper xmlMapper = new XmlMapper();
JsonNode node=xmlMapper.readValue(xml,JsonNode.class);
System.out.println(node.toString());
}
}