Json Recipies – Part 2

Continuing with our earlier post on Json Recipies, let’s explore couple of quick reference recipes using the famous NewtonSoft.Json.

Recipe 04: Deserialize to Anonymous Type

One of the least explored feature in NewtonSoft is the ability to deserialize a Json to anonymous type. For example,

var json = @"{'Name':'anu viswan','Location':'india'}";
var anonymousType = new {Name = string.Empty, Location = string.Empty};

var result = JsonConvert.DeserializeAnonymousType(json, anonymousType);
Console.WriteLine($"Name : {result.Name}, Location:{result.Location}");

This would produce an output as

Name : anu viswan, Location:india

Isn’t that quite useful. You can now deserialize json directly to anonymous types, avoiding the need to declare a type for the purpose or going through tedious task of exploring the JObject. I believe this functionality is quite underused.

Recipe 05: Formatting Json as camelCase.

What if you come across a situation wherein, you want to format the Json with keys in camelCase. For example, consider the following json.

{'FirstName':'Anu','LastName':'Viswan','Age':35}

You would like to format the json such that the keys are rewritten as firstName,lastName and age. This is where CamelCasePropertyNamesContractResolver comes into picture. You could set the ContractResolver to CamelCasePropertyNamesContractResolver using the following.

var json = @"{'FirstName':'Anu','LastName':'Viswan','Age':35}";
var student = JsonConvert.DeserializeObject(json);
var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var result = JsonConvert.SerializeObject(student,camelSettings);

Where Student is defined as

public class Student
{
public string FirstName{get;set;}
public string LastName{get;set;}
public int Age{get;set;}
}

This would format the json string with all keys in camelCase.

So far, we have examined a simple json. Let’s expand the example for a complex nested version that happens to have a property of Type object, which encapsulate the nested json part. For example, what if the json in question is as follows

{"FirstName":"Anu","LastName":"Viswan","age":35,"SkillSet":{"ProgrammingLanguages":"C#,Dart","Database":"Sql Server,MySql,MongoDb"}}

This is where things get interesting. If you were to define a Property of Type Object in the Student Class, you could be suprised that the inner object wasn’t camelCased. Let’s check by adding a Property called SkillSet of Type object in Student.

public class Student
{
public string FirstName{get;set;}
public string LastName{get;set;}
public int Age{get;set;}
public object SkillSet{get;set;}
}

If we were to run the client code using CamelCasePropertyNamesContractResolver as described above, the output would be as following.

{"firstName":"Anu","lastName":"Viswan","age":35,"skillSet":{"ProgrammingLanguages":"C#,Dart","Database":"Sql Server,MySql,MongoDb"}}

As you can observe, the inner Object didn’t have its keys formatted with CamelCase.

The trick lies in most unexpected corner. Infact, you do not even need the Student Class. All you need is the ExpandoObject. Let’s rewrite the client code using ExpandoObject.

var json = @"{'FirstName':'Anu','LastName':'Viswan','Age':35, SkillSet:{ProgrammingLanguages:'C#,Dart',Database:'Sql Server,MySql,MongoDb'}}";
var student = JsonConvert.DeserializeObject(json);

var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var result = JsonConvert.SerializeObject(student,camelSettings);

That’s all the magic you needed. Now the formatting for inner Object is magically fixed.

{"firstName":"Anu","lastName":"Viswan","age":35,"skillSet":{"programmingLanguages":"C#,Dart","database":"Sql Server,MySql,MongoDb"}}

Recipe 06: Search and Replace using JObject.

There might be situations which forces you to use JObject for parsing json. Yes, it is inconvenient way of doing it, but sometimes you need to walk the hard path ( or should I say, sometimes JObject is the most convenient option).

How could you search and replace a token in JObject, especially if you do not know the names of parent node. For example, let us consider the following two json strings.

{'Fields' : { 'CA' : 'P' , 'MA' : { 'COLL': 'Q'} } }
{'Item' : { 'PA' : 'P' , 'VA' : { 'COLL': 'D'} } }

You are supposed to update the Value of COLL. However, as you can observe from the two Jsons available, the parents nodes are different.

Updating COLL would have been tough task. But there are few interesting methods in JObject makes our life easier.

To Select the COL token in either of the Json, you could use the SelectToken method

jobject.SelectToken("$..COLL");

For updating the value, you could use the Replace method. For example,

jobject.SelectToken("$..COLL").Replace(1);

That would give use the output we require. The output of above given samples would be as follows.

// Example 1
{
"Fields": {
"CA": "P",
"MA": {
"COLL": 1
}
}
}

// Example 2
{
"Item": {
"PA": "P",
"VA": {
"COLL": 1
}
}
}

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.