问题
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:
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.Loading the XML into an
XDocument
(orXmlDocument
) and converting the document itself rather than just the root elementXDocument.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