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.

Advertisements

Serialize Deserialize NameValueCollection

Don’t ask me why one cannot Serialize/Deserialize a NameValueCollection, but the workaround for the same is based on conversion to dictionary. I ended up writing extension methods to NameValueCollection for serializing and deserializing the collection.

public static string JSONSerialize(this NameValueCollection _nvc)
{
return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k, k =>_nvc.GetValues(k)));
}
public static void JSONDeserialize(this NameValueCollection _nvc,string _serializedString)
{
var deserializedobject = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(_serializedString);
foreach (var strCol in deserializedobject.Values)
foreach (var str in strCol)
_nvc.Add(deserializedobject.FirstOrDefault(x => x.Value.Contains(str)).Key, str);
}