I am using JSON.NET to convert some XML to JSON.
My XML looks like this:
<Root>
<Product>
<Name />
<Id />
</Product>
<Product>
<Name />
<Id />
</Product>
</Root>
Im converting the xml using this method:
private string ConvertToJson(string xml)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(xml);
var JsonString = JsonConvert.SerializeXmlNode(XmlDoc);
return JsonString;
}
This works fine as long as there is more than one product, JSON.NET will create a JSON array. However if there is only one product JSON.NET will not create a JSON array, but i need it to.
Any way to force it to create a JSON array?
If you know XML schema beforehand you can force array generation by attaching json:Array="true" to the node you want to convert to an array
static string convertToJson(string what)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(what);
var products = doc.GetElementsByTagName("Product");
if (products.Count == 1)
{
var attribute = doc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json");
attribute.InnerText = "true";
var node = products.Item(0) as XmlElement;
node.Attributes.Append(attribute);
}
string json = JsonConvert.SerializeXmlNode(doc);
return json;
}
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