【问题标题】:Force root xml element to be array on json conversion强制根 xml 元素成为 json 转换的数组
【发布时间】:2018-12-14 15:57:00
【问题描述】:

我在下面使用 (http://james.newtonking.com/projects/json) 来强制 XML 节点在转换为 JSON 时成为一个数组:

<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
  <name>Alan</name>
  <url>http://www.google.com</url>
  <role json:Array='true'>Admin</role>
</person>

我得到的是

 {
   "person": {
     "@id": "1",
     "name": "Alan",
     "url": "http://www.google.com",
     "role": [
       "Admin"
     ]
   }
 }

我想要的是

 {
   "person": [
      {
     "@id": "1",
     "name": "Alan",
     "url": "http://www.google.com",
     "role": [
       "Admin"
     ]
    }
   ]
 }

是否可以在根节点上强制数组?

【问题讨论】:

    标签: json xml json.net


    【解决方案1】:

    我可以通过以下方式获得您想要的结果:

    1. json:Array='true' 添加到根元素&lt;person&gt;

      由于您已经将此属性添加到&lt;role&gt;,因此将其添加到根元素也不应该成为负担。

    2. 将 XML 加载到 XDocument(或 XmlDocument)并转换文档本身,而不仅仅是根元素 XDocument.Root

    因此:

    var xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1' json:Array='true'>
      <name>Alan</name>
      <url>http://www.google.com</url>
      <role json:Array='true'>Admin</role>
    </person>";
    
    var xDocument = XDocument.Parse(xml);
    var json1 = JsonConvert.SerializeXNode(xDocument, Newtonsoft.Json.Formatting.Indented);
    

    生成你想要的 JSON:

    {
      "person": [
        {
          "@id": "1",
          "name": "Alan",
          "url": "http://www.google.com",
          "role": [
            "Admin"
          ]
        }
      ]
    }
    

    但以下不是:

    var json2 = JsonConvert.SerializeXNode(xDocument.Root, Newtonsoft.Json.Formatting.Indented);
    

    使用XmlDocument 获得了类似的结果,其中只有以下内容可以正常工作:

    var xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(xml);
    
    var json1 = JsonConvert.SerializeXmlNode(xmlDocument, Newtonsoft.Json.Formatting.Indented);
    

    我在 Json.NET 10.0.1 和 Json.NET 12.0.1 上都确认了这一点。为什么序列化文档与其根元素会有所不同,这有点神秘,您可以为 Newtonsoft 创建一个issue,询问它为什么重要。

    演示小提琴here.

    【讨论】:

    • 是的..它起作用了,根 vs 文档是导致问题的原因。非常感谢您的快速回复。
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2013-03-23
    相关资源
    最近更新 更多