3

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?

CathalMF
  • 9,705
  • 6
  • 70
  • 106
  • And here is an answer specifically tailored to `XmlDocument`: [JSON.Net Xml Serialization misunderstands arrays](https://stackoverflow.com/a/26505198/3744182). – dbc Sep 16 '17 at 21:06
  • I have found a better answer but as this is closed I´ll answer here! add those attributes to your XML node : json:Array="true" xmlns:json="http://james.newtonking.com/projects/json" If you are generating your xml from Json convert you can use the method JsonConvert.DeserializeXmlNode(json, "RootName", true); where the third parameter is "Write Array Attribute" – Daniel Apr 22 '19 at 17:43

2 Answers2

10

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;
}
orhtej2
  • 2,133
  • 3
  • 16
  • 26
0

It shouldn't impact too much in your performance if you create an array of objects in your code from your XML doc (you need to know the content structure and use POCO objects) and then serialize that list with json. Makes it sense in your case?

Juan
  • 2,156
  • 18
  • 26