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 = @"{
    ""complexFoo"": {
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);

 <root type="object">
   <foo type="string">bar</foo>
   <complexFoo type="object">
     <subFoo type="string">subBar</subFoo>

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

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.

  2. Hello admin i see you don’t monetize your site. You can earn additional bucks
    easily, search on youtube for: how to earn selling

Leave a Reply to Dinesh Cancel reply

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

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

Facebook photo

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

Connecting to %s

%d bloggers like this: