Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force JSON.NET to convert xml to json array [duplicate]

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?

like image 250
CathalMF Avatar asked May 07 '26 15:05

CathalMF


1 Answers

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;
}
like image 88
orhtej2 Avatar answered May 09 '26 03:05

orhtej2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!