加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:50:08 所属栏目:百科 来源:网络整理
导读:我有一些 XML格式的简单数据,我需要将其转换为 JSON,并且能够将 JSON转换回相同的XML字符串.但是我在使用现有的jackson(版本2.0.6)库时遇到了问题. 这是具有类似结构的XML数据的示例 channels channelA/channel channelB/channel channelC/channel/channels
我有一些 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. Has anyone written a custom deserializer to support this feature? Or is there another way to work around this.
  2. How do I preserve the root element name?

以下是一个测试示例

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

解决方法

这里真正重要的是你的类 – 只是显示XML本身并不能提供足够的信息来了解正在发生的事情.

我怀疑你需要杰克逊2.1(一旦它在一两周内发布),因为它最终支持“解开的列表”.在此之前,只有“包装”列表才能正常工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读