Convert JSON to XML in .NET

I was working on a project where we were receiving data in a JSON-like format, and we needed the ability to extract values by field name. After doing just a bit of research, I found that the .NET Framework has a JsonReaderWriterFactory class that allows you to create an XmlDictionaryReader that processes JSON data.

Converting JSON to XML is perfect for my needs because it allows me to use LINQ to XML to query and retrieve the values I’m looking for. So, I wrote a few regular expressions to transform the JSON-like format into actual JSON. Then I used the JsonReaderWriterFactory to do the conversion and loaded the resulting XML into an XDocument.

Here’s an example.

const string json = @"{
    ""foo"":""bar"",
    ""complexFoo"": {
        ""subFoo"":""subBar""
    }
}";
byte[] bytes = Encoding.ASCII.GetBytes(json);
using (var stream = new MemoryStream(bytes))
{
    var quotas = new XmlDictionaryReaderQuotas();
    var jsonReader = JsonReaderWriterFactory.CreateJsonReader(stream, quotas);
    var xml = XDocument.Load(jsonReader);
    Console.WriteLine(xml);
}

/*--------
 Output:
 <root type="object">
   <foo type="string">bar</foo>
   <complexFoo type="object">
     <subFoo type="string">subBar</subFoo>
   </complexFoo>
 </root>
--------*/
Advertisements

5 thoughts on “Convert JSON to XML in .NET”

  1. Is there an easy way how to make such conversion not to load whole json input into memory? If you have large json file you need to convert it on the fly from a file to new file without any need to load whole content into ram.
    Thanks ahead for any hints.

    1. Thanks Adam for the answer. The link has some good points inthere. But I am aiming for a generic json-file-to-xml-file converter without any knowledge of whats inside the json. So I probably need to avoid deserialization to any object. Best solution i came up with so far is using JsonTextReader, read the files token by token and define conversion for each token type to some xml part and use XmlWriter to store directly to a file. If you have some better idea than please let me know. Thanks again.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s