I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to XML format and viceversa?
Yes. Using the JsonConvert class which contains helper methods for this precise purpose:
Documentation here: Converting between JSON and XML with Json.NET |
|||||||||||
|
Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:
|
|||
|
Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. Keep in mind I am using the default settings with Newtonsoft json library and MS XML library, so your mileage may vary: XML->JSON
JSON->XML
Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. |
||||
|
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 |
|||
|
Try this function. I just wrote it and haven't had much of a chance to test it, but my preliminary tests are promising.
|
|||
|
I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly / project. I came up with the following thanks to the source code of the DynamicJson project:
Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from json to Xml, there are various ways to do the opposite. |
||||
|
mmhhh... I found some problems in this code, if for example the document didn't have any line feed, the code could not work (I have to convert a "only one line json document"). Also, it was changing a lot of my data (I have : and " in the data values). But it was a very good start for me to implement the procedure. I publish it, just:
Ciao, Michele |
|||
|
I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) -- there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations. But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both. |
||||
|