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"}}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Can a local .xml file be used in place of the xml string in the Loadxml()?
@cardiac7 Yes you can use any XmlDocument for that. It does not matter how the object was filled with XML.
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"}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.