9

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"}}
98374598347934875
  • 535
  • 1
  • 4
  • 12

2 Answers2

19

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.

98374598347934875
  • 535
  • 1
  • 4
  • 12
  • in my case i have a wcf method from which i need to return json string. Dataset > xml> json but when i am converting into json string than i am encountering the same problem. my method signature : [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/methosnamenamespoace?querystring")] string mthodname(args); what should i return in case to get proper json on other end. Please Guide. – Rajiv yadav Aug 08 '12 at 13:17
  • Can a local .xml file be used in place of the xml string in the Loadxml()? – cardiac7 May 28 '15 at 15:11
  • 1
    @cardiac7 Yes you can use any `XmlDocument` for that. It does not matter how the object was filled with XML. – Koopakiller Aug 05 '15 at 12:07
0

when you will access data then / automatically does not show . I am accessing in HTML5 help of AJAX post . Result is showing

in C# result is showing that "{\"person\":{\"name\":\"John\"}}"

But in HTML5 , it is working fine {"person":{"name":"John"}}