使用jackson将带有重复元素的XML转换为JSON

时间:2012-09-14 15:00:35

标签: java xml jackson xml-deserialization

我有一些XML格式的简单数据,我需要转换为JSON,并且能够将JSON转换回相同的XML字符串。但是我在使用现有的jackson(版本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
    ;
}

所以我的问题是

  
      
  1. 是否有人编写了自定义反序列化程序来支持此功能?或者还有另一种解决方法。
  2.   
  3. 如何保留根元素名称?
  4.   

以下是测试示例

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());
  }
}

0 个答案:

没有答案