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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 13:22:17

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6861708/how-to-serialize-xml-to-a-json-object-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!