JsonConvert.SerializeXmlNode() adds extra child for arrays

Viewed 80

I am using JsonConvert.SerializeXmlNode() to serialize a xml node:

var doc = new XmlDocument();
doc.LoadXml(xml.ToString());
jsonRequest = JsonConvert.SerializeXmlNode(doc);

here is an example xml array

<cars>
   <car>
     <id>0001</id>
   </car>
   <car>
     <id>0002</id>
   </car>
</cars>

this would become:

{
   "cars" : {
       "car" : [{
          "carId" : "0001"
       }, {
          "carId" : "0002"
       }]
   }
}

Is there a way to serialize the array like this?

{
   "cars" : [{
          "carId" : "0001"
       }, {
          "carId" : "0002"
       }
   ]
}
1 Answers

I believe XElement is a better choice while dealing with xml, as its newer. I wrote a quick code and tested, it works all good, may be its not well optimized and ideal but its here to show you the way to go, hope it will help.

var xml = @"<cars><car><id>0001</id></car><car><id>0002</id></car></cars>";

XElement doc = XElement.Parse(xml);

var cars = new
{
    cars = (from c in doc.Descendants("car")
            select new { carid = c.Element("id").Value }
            ).ToList()
};

var json = JsonConvert.SerializeObject(cars);

Console.WriteLine("Json: {0}", json.ToString());

just copy paste in your console app and see if that's what you were looking for.

Related