Force root xml element to be array on json conversion

北战南征 提交于 2019-12-24 11:30:52

问题


I am using below (http://james.newtonking.com/projects/json) to force XML nodes to be an array when converted to 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>

and what I get is

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

What I wanted is

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

Is it possible to force array on root node ?


回答1:


I am able to get the result you desire by:

  1. Adding json:Array='true' to the root element <person>.

    Since you are already adding this attribute to <role> adding it to the root element as well should not be a burden.

  2. Loading the XML into an XDocument (or XmlDocument) and converting the document itself rather than just the root element XDocument.Root.

Thus:

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

Generates the JSON you want:

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

But the following does not:

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

A similar result obtains using XmlDocument, in which only the following works as desired:

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

var json1 = JsonConvert.SerializeXmlNode(xmlDocument, Newtonsoft.Json.Formatting.Indented);

I confirmed this on both Json.NET 10.0.1 and Json.NET 12.0.1. It's a bit mysterious why serializing the document vs. its root element should make a difference, you might create an issue for Newtonsoft asking why it should matter.

Demo fiddle here.



来源:https://stackoverflow.com/questions/53783053/force-root-xml-element-to-be-array-on-json-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!