I can serialize XML to a JSON string like this:
var xml = new XmlDocument();
xml.LoadXml("<person><name>John</name></person>");
string jsonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.None);
Response.ContentType = "application/json";
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(jsonString));
That would give me:
"{\"person\":{\"name\":\"John\"}}"
But how can I serialize it to a JSON object? Like this:
{"person":{"name":"John"}}
Sometimes we just want to make it harder than it is ...
var xml = new XmlDocument();
xml.LoadXml("<person><name>John</name></person>");
Response.ContentType = "application/json";
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(xml));
What I did wrong was to serialize the XML into a string and then serialize it again.
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