【问题标题】:XML to JSON - unexpected behaviour while converting lists?XML 到 JSON - 转换列表时出现意外行为?
【发布时间】:2016-02-01 14:09:25
【问题描述】:

这是我的 json 值:

{
    "hello": [
        {
            "names": {
                "name": "abc"
            }
        },
        {
            "names": {
                "name": "def"
            }
        }
    ]
}

我尝试使用XML.toString(new JsonObject()),结果如下:

   <hello>
       <names>
          <name>abc</name>
       </names>
   </hello>
   <hello>
       <names>
          <name>def</name>
       </names>
   </hello>

然而,我期望的 xml 是这样的:

   <hello>
       <names>
          <name>abc</name>
       </names>
       <names>
          <name>def</name>
       </names>
   </hello>

这种意外行为会导致无效的 XML 错误,因为现在没有根元素。我在这里想念什么?

【问题讨论】:

  • 你的意思是XML.toString(new JsonObject())?
  • @Rehman:除了 XML.toString(new JSONObject(string)) 之外,没有其他重要的代码。
  • @ᴳᵁᴵᴰᴼ:编辑了问题。谢谢!

标签: java json xml


【解决方案1】:

您的 JSON 代码中的问题。 [] 表示数组,根据定义,数组是元素的集合。所以生成的 xml 代码包含 hello 元素的 set。尝试将您的[] 更改为{}

{
    "hello": {
        "names": [
            {
                "name": "abc"
            },
            {
                "name": "def"
            }
        ]
    }
}

刚刚试了一下,得到了您正在寻找的确切输出:

<hello>
    <names>
        <name>abc</name>
    </names>
    <names>
        <name>def</name>
    </names>
</hello>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2017-03-16
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多