Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Serialize XML to a JSON object with Json.NET

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"}}
like image 471
98374598347934875 Avatar asked Jul 28 '11 15:07

98374598347934875


1 Answers

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.

like image 124
98374598347934875 Avatar answered Oct 05 '22 23:10

98374598347934875