In this post, I am sharing how to use Json.Net to map Json response with class in C#.
Json.Net is a popular high-performance JSON framework for .NET
Prerequisite:
Json.Net : Install with Nuget Package Manager in Microsoft Visual Studio
Example 1: Using JsonConvert.DeserializeObject Method to map Json response with class
One way is to use JsonConvert.DeserializeObject Method which automatically map the data from valid Json response to class. However, in this case the structure and hierarchy of the classes must match with the Json response. You can use JSON C# class generator tools online where you have to pass Json response and it will generate C# classes for you.
Let's assume we have below Json Response
Now let's generate classes using one of the tools online JSON C# Class Generator Tool
We get below classes for our above Json response.
Now we have classes mapped with Json response. Now use below code to map the data from Json response to classes.
Example 2: Using JObject & JToken classes
Now let's assume we have below Json response where parent node for the product data is dynamic which is productid.
Json Response
In this case we would use JObject & JToken to fetch the product data as we would not able to generate the static classes for this scenario as the parent node has dynamic values which would change on run-time.
Json.Net is a popular high-performance JSON framework for .NET
Prerequisite:
Json.Net : Install with Nuget Package Manager in Microsoft Visual Studio
Example 1: Using JsonConvert.DeserializeObject Method to map Json response with class
One way is to use JsonConvert.DeserializeObject Method which automatically map the data from valid Json response to class. However, in this case the structure and hierarchy of the classes must match with the Json response. You can use JSON C# class generator tools online where you have to pass Json response and it will generate C# classes for you.
Let's assume we have below Json Response
{ "response": { "status": 1, "httpStatus": 200, "products": [ { "id": "1", "name": "Product-1", "price": "100", "image_url": "~/Images/prod1.jpg" }, { "id": "2", "name": "Prod1", "price": "200", "image_url": "~/Images/prod2.jpg" } ], "errors": [], "errorMessage": null } }
Now let's generate classes using one of the tools online JSON C# Class Generator Tool
We get below classes for our above Json response.
public class Product { public string id { get; set; } public string name { get; set; } public string price { get; set; } public string image_url { get; set; } } public class Response { public int status { get; set; } public int httpStatus { get; set; } public IList<product> products { get; set; } } public class Example { public Response response { get; set; } }
Now we have classes mapped with Json response. Now use below code to map the data from Json response to classes.
static void Main(string[] args) { List<Product> products = new List<Product>(); Example res = new Example(); res = getResponse(); foreach (Product p in res.response.products) { Console.WriteLine(string.Format("Product Id: {0}", p.id)); Console.WriteLine(string.Format("Product Name: {0}", p.name)); Console.WriteLine(string.Format("Product Price: {0}", p.price)); Console.WriteLine(string.Format("Product Image URL: {0}\n", p.image_url)); } Console.Read(); } public static Example getResponse() { string json = @"{ ""response"": { ""status"": 1, ""httpStatus"": 200, ""products"": [ { ""id"": ""1"", ""name"": ""Product-1"", ""price"": ""100"", ""image_url"": ""~/Images/prod1.jpg"" }, { ""id"": ""2"", ""name"": ""Prod1"", ""price"": ""200"", ""image_url"": ""~/Images/prod2.jpg"" } ] } }"; return JsonConvert.DeserializeObject<Example>(json); }OUPTUT
Example 2: Using JObject & JToken classes
Now let's assume we have below Json response where parent node for the product data is dynamic which is productid.
Json Response
{ "response": { "status": 1, "httpStatus": 200, "products": { "1": { "id": "1", "name": "Product-1", "price": "100", "image_url": "~/Images/prod1.jpg" }, "2": { "id": "2", "name": "Prod1", "price": "200", "image_url": "~/Images/prod2.jpg" } }, "errors": [], "errorMessage": null } }
In this case we would use JObject & JToken to fetch the product data as we would not able to generate the static classes for this scenario as the parent node has dynamic values which would change on run-time.
static void Main(string[] args) { List<product> products = new List<product>(); products = getProductDetails(); foreach (Product p in products) { Console.WriteLine(string.Format("Product Id: {0}", p.id)); Console.WriteLine(string.Format("Product Name: {0}", p.name)); Console.WriteLine(string.Format("Product Price: {0}", p.price)); Console.WriteLine(string.Format("Product Image URL: {0}\n", p.image_url)); } Console.Read(); } public static List<product> getProductDetails() { List<product> products = new List<product>(); Product product = null; string json = @"{ ""response"": { ""status"": 1, ""httpStatus"": 200, ""products"": { ""1"": { ""id"": ""1"", ""name"": ""Product-1"", ""price"": ""100"", ""image_url"": ""~/Images/prod1.jpg"" }, ""2"": { ""id"": ""2"", ""name"": ""Prod1"", ""price"": ""200"", ""image_url"": ""~/Images/prod2.jpg"" } }, ""errors"": [], ""errorMessage"": null } }"; JObject data = JObject.Parse(json); JObject Products = (JObject)data["response"]["products"]; foreach (var x in Products) { JToken prod = x.Value; product = new Product(); product.id = prod["id"].ToString(); product.name = prod["name"].ToString(); product.price = prod["price"].ToString(); product.image_url = prod["image_url"].ToString(); products.Add(product); } return products; }OUTPUT