Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Tuesday, October 29, 2019

NewtonSoft Json Test pad

Nearly for the last 10 months half the time in my day job, I am working with Microsoft on optimizing the performance of our flagship application. Not really my current company's application but for the client which is one of the big 4 auditing firms. Sorry, as per NDA, I am not allowed to reveal the client name:)

It is a legacy application someone started in what we now call classic VB when I was in high school. It then converted to .Net then to WPF, then made SOA finally in AngularJS 1.X. I don't think its really converted but people started calling it in different technology. Nothing in WPF blocks you writing code in the WinForms way. It's really a legacy giant with 100s of .vbproj & .csproj files.

One of the problems we discovered was the JSON serialization. Though developers wanted to use NewtonSoft.JSON, they were using JavaScript serializer as that is the built-in JSON serializer in .Net. For using built in things, they don't need additional permissions. At some point, Microsoft figured out from the performance tuning data (perfview.exe) that the JavaScriptSerializer is slow than the NewtonSoft.JSON serializer. Though we all knew the fact, we never expected Microsoft telling that it is the bottleneck in the system and needs to be fixed.

It is declared that the NewtonSoft.JSON serializer would be the defacto serializer going forward. Developers started changing JavaScriptSerializer to NewsonSoft. 

One of the tools which came to demand is a test pad for NewtonSoft.JSON. Given a JSON string, how to easily develop the query to find something in JSON via NewtonSoft.JSON. We can easily use Linq but some are easy with the SelectToken(). We started searching for an online NewtonSoft test pad something similar to JSFiddle. Or some desktop tools similar to LINQPad.

After a good amount of googling ended up using https://dotnetfiddle.net. That has support to add nuget packages. Even we didn't have to start from scratch. Fork the below snippet to start with. 

https://dotnetfiddle.net/QQbpk5

Happy coding...

Tuesday, April 19, 2016

Deserialize JSON string to C# dynamic type

Introduction

This is the age of APIs in computer science. To be more specific web APIs. Don't get confused with the specific technology of .Net Web API. Any methods or resources which are exposed via URL in a structure is an API. From our apps we can call them to do achieve the functionality.

Resources are now a days exposed via ReST protocol and the format is JSON. It works well with JavaScript. But when coming to .Net world, its little difficult to keep the JSON as is in our app. Often we need to convert those resources into entity classes. Creating entity class for each API response is a tricky tasks. It puts more time to complete the API integration tasks. Often after using one API for months we may need to switch to another API providing same service. At that time we need to rewrite it. Creating classes to get exact replica of response is really difficult to manage.

But its always suggested to have entity classes which are for our application regardless of the API we are using. As soon as we got the response from the web API, we should convert the response to our model and that should go on from that point on wards.

Dynamic object to hold JSON

In the beginning people were programming without type safety. Then the strong typed languages were introduced and everybody went behind that. Now its the time everybody again going to dynamic typing. May be its because of JavaScript's success.

VB always gave us the option to have dynamic typing. But in C# its introduced with .Net 4.0. The dynamic keyword is introduced to denote the variables which are not type safe. In other words a type which we don't know at compile time, what it is going to contain. Kind of key value store / dictionary.

Enough theory. Below is the code to convert a GitHub API response. The API url is 

private Project GetProjectFromJSON(string json)
{
    JavaScriptSerializer ser = new JavaScriptSerializer();
    dynamic projectNode = ser.Deserialize<dynamic>(json);
    return new Project()
    {
        Name = projectNode["name"],
        Description = projectNode["description"],
        SourceUrl = projectNode["html_url"],
        Url = projectNode["homepage"]
    };
}

JavaScriptSerializer is a .Net framework class. We don't need to add any dependency to third parties. There are other .Net libraries which are helping to convert JSON to dynamic object but those will add unwanted dependencies. Hope this is self explanatory.

Important thing to note here is the usage of dynamic. Do not ever return dynamic to outer world. This method should hide the complexities of getting the project from GitHub. The consumers of this method then don't need to change when the logic of GitHub API interaction changes.

More details about usage in real application can be seen in this file.