强制根xml元素在json转换时为数组

时间:2018-12-14 15:57:01

标签: json xml json.net

我正在使用下面的(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"
     ]
    }
   ]
 }

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

1 个答案:

答案 0 :(得分:0)

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

  1. json:Array='true'添加到根元素<person>中。

    由于您已经将该属性添加到<role>中,因此也将其添加到根元素中不会成为负担。

  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