tags:

views:

6291

answers:

4

I started to use JSON.Net to convert a string in json format to object or vice visa. I am not sure in the JSON.Net framework, is it possible to convert a string in json to xml format and vice visa?

+5  A: 

Yes. Using the XmlNodeConverter class:

XmlNodeConverter converter = new XmlNodeConverter();
// Create an XmlDocument from a JsonReader
XmlDocument doc = converter.ReadJson(myJsonReader, typeof(XmlDocument));
// Write an XmlNode to a JsonWriter
converter.WriteJson(myJsonWriter, myXmlNode);
David Brown
I could not find this class. I use NewtonSoft Json.net 3.5.
David.Chu.ca
It appears this functionality has been moved to the Newtonsoft.Json.Converters.XmlNodeConverter class in JSON.NET 3.5: http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Converters_XmlNodeConverter.htm
David Brown
I looked at there but your examples codes are not there. Any example codes to use the new libraries to do the conversions?
David.Chu.ca
The link I posted in my previous comment has all of the information you need. But I'll edit my answer anyway...
David Brown
A: 

I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole... :-/); but if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction).

StaxMan
Heh -- so many idiots in the world, doing stupid things, being offended when called out. I cherish all the minus votes in this case.
StaxMan
+3  A: 

Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:

XmlNote myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString);
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);
David.Chu.ca
+1  A: 

Here is a blog that tells about conversion of XML to JSON and JSON to XML: http://sandeep-aparajit.blogspot.com/2010/01/json-to-xml-and-xml-to-json-converter.html

Eric