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
}
}
}

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 )

Google photo

You are commenting using your Google 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