I am trying to create a JSON from an xml using JSON.NET
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson); //xmlPerson is the xml from above
JObject personDefinition = JObject.Parse(JsonConvert.SerializeObject(docPerson));
Tasks.personDefinition = personDefinition["personDefinition"];
OUTPUT JSON
"person":{"person":[{"personId":"1","firstName":"Name1","lastName":"lastName1"}, {"personId":"3","firstName":"Name2","lastName":"lastName2"}]}
I don't need the outer person and just need the following json
REQUIRED JSON
"person":[{"personId":"1","firstName":"1","lastName":"Weight"},{"personId":"3","firstName":"4","lastName":"Pulse Ox"}]}
I have tried using the .first method however it is throwing an error. Can anyone suggest on how to strip the root from the output json
JSON.Net has a SerializeXmlNode()
method that can do exactly what you want. Simply pass true
to the omitRootObject
parameter.
Observe:
string xmlPerson = @"<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson);
string json = JsonConvert.SerializeXmlNode(docPerson, Formatting.None, true);
Console.WriteLine(json);
Output:
{"Person":[{"name":"Nicolas","age":"22"},{"name":"Pankaj","age":"25"}]}
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