I am currently using Newtonsoft to convert some xml to json to return from a RestExtension.
My xml is in the form of
<Items>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
</Items>
I convert this to json using
JsonConvert.SerializeXmlNode(xmldocument);
This works fine if there is more than one item.
I get this - an array of items in json (which is what I need):
{"Items":{"Item":[{"Name":"name","Detail":"detail"},{"Name":"name","Detail":"detail"}]}}
But when there is only one it quite understandably converts like this (not an array):
{"Items":{"Item":{"Name":"name","Detail":"detail"}}}
My app developer who is reading this needs the json to return an array of items regardless or whether there is one or more.
Is there a way of tricking it into thinking it's an array or can someone suggest another way of doing this?
{} denote containers, [] denote arrays.
To convert an XML document to JSON, follow these steps: Select the XML to JSON action from the Tools > JSON Tools menu. Choose or enter the Input URL of the XML document. Choose the path of the Output file that will contain the resulting JSON document.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
Read this documentation about Serialize Xml Node
You can force JSON Array this way
var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >
<Item json:Array='true'>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
</Items>";
DEMO
In case it helps anyone, further to meda's reply. Here's how you make this work with XElement rather than xmlTextWriter and XDocument
XNamespace ns = "http://james.newtonking.com/projects/json";
var items = new XElement("items",new XAttribute(XNamespace.Xmlns+"json",ns));
items.Add(new XElement("item",new XAttribute(ns+"Array",true),
new XElement("name", "name"),
new XElement("Detail", "detail")));
then to convert it
XmlDocument doc = new XmlDocument();
doc.LoadXml(items.ToString());
var converted JsonConvert.SerializeXmlNode(doc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With