【问题标题】:Converting a XML string into a JSON string is not giving desired outcome将 XML 字符串转换为 JSON 字符串不会产生预期的结果
【发布时间】:2014-07-14 13:48:16
【问题描述】:

我正在使用 NewtonSoft.JSON 来解析 XML 文档并构建 JSON 字符串,但我没有得到想要的输出。我的 xml 字符串在下面给出

<fulfillment>
       <tracking_number/>
        <line_items>
              <id>466157049</id>
              <quantity>1</quantity>
          </line_items>
   </fulfillment>

在将 XML 转换为 JSON 后,它会给出以下 JSON

{"fulfillment":{"tracking_number":"er2222222","line_items":{"id":"464194075","quantity":"1"}}}

但我需要如下 JSON,因为我的 XML cam 包含多个 line_items 数据。JSON 上方和下方的区别在于 line items 元素之后的数组括号。当我在 xml 中使用两个 line_items 时,它会给出所需的结果,但使用单个 line_items 它不会在 line_items 部分返回类似于 JSON 格式的数组。

{"fulfillment":{"tracking_number":"er2222222","line_items":[{"id":"464194075","quantity":"1"}]}}

解决问题的出路是什么。

谢谢 乌特帕尔梅蒂

【问题讨论】:

    标签: json json.net


    【解决方案1】:

    您需要在 xml 中进行一些更改。它应该是这样的:

    <fulfillment xmlns:json='http://james.newtonking.com/projects/json'>
      <tracking_number>er2222222</tracking_number>
      <line_items json:Array='true'>
        <id>466157049</id>
        <quantity>1</quantity>
      </line_items>
    </fulfillment>
    

    使用 JSON.NET 序列化此 xml 示例将产生您需要的 json 字符串。添加多个line_items 节点将产生预期的结果。多个line_items 的示例:

    <fulfillment xmlns:json='http://james.newtonking.com/projects/json'>
      <tracking_number>er2222222</tracking_number>
      <line_items json:Array='true'>
        <id>466157049</id>
        <quantity>1</quantity>
      </line_items>
      <line_items>
        <id>466157050</id>
        <quantity>2</quantity>
      </line_items>
    </fulfillment>
    

    使用上述 xml 示例调用以下代码:

    var xml = new XmlDocument();
    xml.Load("Location of the xml file");
    var jsonStr = JsonConvert.SerializeXmlNode(xml);
    

    将产生以下 json 字符串:

    {
        "fulfillment": {
            "tracking_number": "er2222222",
            "line_items": [
                {
                    "id": "466157049",
                    "quantity": "1"
                },
                {
                    "id": "23",
                    "quantity": "2"
                }
            ]
        }
    

    【讨论】:

    • 感谢您的回复。但是有没有其他方法可以在不改变文档结构的情况下做到这一点,因为这个 XML 来自不同的来源,我不能轻易修改结构。
    • 这是我所知道的方式。但是如果你将xml加载到XmlDocument并且你知道它的结构,你总是可以添加你需要的属性并将xml序列化成适合你的json格式。
    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 2017-06-07
    • 2012-10-26
    • 2019-10-29
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多