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> --------*/
Is there a way can we get rid of Type=”object” or Type=”string” etc from above code?
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.
See if this helps. You can serialize or deserialize directly to or from a stream.
http://www.newtonsoft.com/json/help/html/performance.htm
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.
Hello admin i see you don’t monetize your site. You can earn additional bucks
easily, search on youtube for: how to earn selling
articles