Skip to main content

Generic class to map JSON data to MVC Models

Many a times we have to use data we get from web services in our application. When we use generic classes to convert data like a dataset to JSON we sometimes get data wrapped into another JSON key value. Say for e.g. your data looks like –


If this value is returned as table, then the dataset is converted to JSON as –


When it is a dataset which is converted to JSON, most of the times it is a collection which could be mapped to a model. The resultant JSON could look like –
{“table”:[{“key”:”value1”,  “username”:”myname”}, {“key”:”value2”,  “username”:”yourname”}]}
This needs to be mapped to a model class user –
    public class User
        public string key;
        public string username;
If we try to deserialize this JSON object we need to map it to an object of class UserCollection which looks like –
    public class UserCollection
        public List<User> table;
This is required for the JSON data to be properly mapped to a C# object. But “table” is kind of an inappropriate name for a data member. We can name it to; umm say, UserList. But the process to deserialize the JSON data requires exact name for the key and the data member. But we cannot name data members as per their JSON counterparts. The solution is to use [JsonProperty]. We can provide the name of the JSON key as [JsonProperty(“table”)]. See e.g. –
    public class UserCollection
        public List<User> UserList;
This would ensure that the model is mapped to the appropriate JSON structure.
Now let’s move on to our original problem. We cannot be creating collection classes for each model class. So, we would create a generic class which we would use for each such situation –
    class T { };
    public class JsonCollection<T>
        public List<T> ItemList;
And we would create another class to deserialize the data for us. For reasons of brevity, we would create a class function i.e. a static member function.
using System.Collections.Generic;
using Newtonsoft.Json;

    public class JsonList<T>
        public static List<T> GetItems(string jsonString)
            JsonCollection<T> items = JsonConvert.DeserializeObject<JsonCollection<T>>(jsonString);
            return items.ItemList;
We can also create an instance function but it is not required as such as this is a stateless operation. This would be called as –
List<User> userList = JsonList<User>.GetItems(jsonString);
To user any other model, just replace the type and the data.
One issue that one would encounter is that what if the data is not wrapped around “table”. I had thought of using a dynamic property name, have not tried it. I thought it would not work. Moreover, in the call to deserialize it we do not instantiate any object ourselves. We just pass the data and the required type.
If anyone finds a solution to this, just let me know!

- Vivek


Popular posts from this blog

Count and Label DNA strands

This is a proof of concept (POC) developed using Python3, NumPy, and OpenCV, to count and label the number of DNA strands from an image of combed DNA molecules.
The technique of Adaptive Mean Thresholding is used here.
There are several Thresholding algorithms available.

Assembla hit by a virus?

Today hosted task management site Assembla was hit by some virus. Around 3 hours back we got Service Unavailable - DNS failure error when trying to access the portal.
Trying to call any API from Assembla returns with the following unwanted HTML code prepended to the response:
<html><head><meta http-equiv="refresh" content="0; URL="></head><body><a href="">Please click here</a></body></html>
We have logged a ticket with them. The response was quick but when we tried to post a reply comment we consistently got error - Your CAPTCHA words didn't match We'll keep on chasing them for updates and hope safety for Assembla users.

- Vivek

Of Imitation, Innovation, Inspiration and Improvisation

Copy-paste was never easier, thanks to modern technology. Ideas and innovations now spread even faster. When a product is launched in the market, within a few days, we have other vendors with a similar offering. The case is more severe with mobiles and tablets.