Json Recipes

Here are few quick recipes with Newtonsoft.Json

Recipe 01 : Convert Json to XML

One way to convert a Json to XML would be to convert Json to intermediate class structure and then serialize the class using XMLSerializer. But why go the long way when you can do it directly.

Let’s check the code straightaway.

var jsonString = @"{
'Family':[
{
'Name':'Anu',
'Age': '35'
},
{
'Name':'Jia',
'Age': '2'
}
]
}";
var xml = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString,"root");

That’s it, you have your XML. Output is shown below.

<root>
<Family>
<Name>Anu</Name>
<Age>35</Age>
</Family>
<Family>
<Name>Jia</Name>
<Age>2</Age>
</Family>
</root>

Recipe 02 : Convert XML to Json

No prizes for guess how to do it other way around (XML to Json) – Yes, you Serialize.

var xmlString = @"<root>
<Family>
<Name>Anu</Name>
<Age>35</Age>
</Family>
<Family>
<Name>Jia</Name>
<Age>2</Age>
</Family>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
var json = JsonConvert.SerializeXmlNode(doc);

Recipe 03: Dynamic Json
Consider the following Json. What could be the best way to model it in C# class.

{
'Key1' : 'some value 1',
'Key2' : 'some value 1',
'Key3' : 'some value 1',
'Key4' : 'some value 1',
}

Where you do not know how many Keys would be there and what could be there name ? The easiest way would be if you can serialize it to an Dictionary. The ‘JsonExtensionData‘ attribute allows you to do exactly the same.

<br />public class JsonSample
{
[JsonExtensionData]
public Dictionary<string,object> RandomKeyValuePair {get;set;}
}

// Client Code
var jsonString = @"
{
'Key1' : 'some value 1',
'Key2' : 'some value 1',
'Key3' : 'some value 1',
'Key4' : 'some value 1',
}";

var jsonSampleObject = JsonConvert.DeserializeObject<JsonSample>(jsonString);

Of course the reverse is also possible.

var jsonResult = JsonConvert.SerializeObject(jsonSampleObject);

More recipes later.

Advertisement

One thought on “Json Recipes

Leave a Reply

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 )

Connecting to %s