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>
--------*/
Advertisement
%d bloggers like this: