我有一些简单的XML格式数据,需要将其转换为JSON,并能够将JSON转换回相同的XML字符串。但是我在使用现有的Jackson(版本2.0.6)库时遇到了问题。
以下是类似结构的XML数据示例:
为了能够将其转换回原始XML,我希望JSON看起来像这样。
然而,Jackson让我感到困惑。
以下是类似结构的XML数据示例:
<channels>
<channel>A</channel>
<channel>B</channel>
<channel>C</channel>
</channels>
为了能够将其转换回原始XML,我希望JSON看起来像这样。
{
"channels": {
"channel": [
"A",
"B",
"C"
]
}
}
然而,Jackson让我感到困惑。
{"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());
}
}