Working With JSON Data in C#



Welcome Friends, Thanks for like or share my portal in last few days……..

Today Iam going to give you all the Guys Tutorials on JSON Data  in C#.JSON is same like as XML but JSON is more efficient then that’s why every developer want to work with JSON.So without wasting out time let’s start out tutorial ...

Introduction

JSON (JavaScript Object Notation) is a type of Universal data-interchange format. It is language-independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is very popular nowadays in the developers line.

JSON represents objects in structured text format and data stored in key-value pairs. Many third-party which controls and supply data from client size to server-side in JSON string format so it is necessary to cast our JSON string to all of the objects to access data.There are many ways for working with JSON in C# code or any programming languages.

Using Newtonsoft Libraries in C#

Newtonsoft is also known as Json.NET. It is a high-performance JSON framework for .NET. It is very easy to use and much faster than the built-in JSON serializes of .NET.

Using JsonConverter in Visual Studio

 

JsonConvert() class has a method to convert to and from JSON string, SerializeObject() and DeserializeObject() respectively. It can be used where we won't to convert to and from a JSON string.

Iam going to show a small example which will give you a demo to use it in Projects, I have used “JsonConvert.DeserializeObject” method to cast my JSON object to my main class object. Here JSON key name must match with the class property name and matching is case insensitive.

static void Main(string[] args)   
{  
json_data = @ "{  
'first_name': 'Anthoney', 'last_name': 'Singh
}  
";  
var Data = JsonConvert.DeserializeObject <Data> (jsonData);  
Console.WriteLine(string.Concat("Start", Data.first_name, "" + Data.last_name));  
Console.ReadLine();  
}  

public class Data
{  
public string first_name{  
get;  
set;  
}  
public string last_name {  
get;  
set;  
}  
}  


Using Jobject.Parse

JObject( ) class is used as a parse method, it parses the JSON string and converts it into a Key-value dictionary object. Iam going to show a small example which will give you a demo to use it in Projects,  I have used “JObject.Parse” method and retrieved data using key.

string json_data = @"{  
'first_name':'Anthony',  
'last_name:'Singh'
}";  

var Data = JObject.Parse(jsonData);  
Console.WriteLine(string.Concat("Start", Data["first_name"], "" + Data["last_name"]));  

Console.ReadLine(); 

Code above starting all the codes are given, we have used JObject.Parse method output to dynamic object and access value as properties of dynamic object.

string json_data = @"{  
'first_name':'Anthony',  
'last_name:'Singh'
}";  
dynamic data = JObject.Parse(jsonData);  

Console.WriteLine(string.Concat("Hi ", data.first_name, "" + data.last_name));  
Console.ReadLine();  

Note that in the above-described method property name or key name is case sensitive. for example, property name of class must match key of JSON data.


Using Data Contract Json Serializer class in C#

The .NET framework provided some important classes for serializing and de-serializing to JSON. One of them is DataContractJsonSerializer. Using the following code we can deserialize the JSON object.

To use this method in our projects we have to remember below points :-

·         The project must have a reference System.Runtime.Serialization library
·         The class must decorate with DataContract and properties decorate with DataMember attributes
·         Use WriteObject method for serializing an object and use ReadObject method for deserializing a JSON object.

static void Main(string[] args)  
{  
string json_data = "{ \"first_name\":\"Anthony\",\"last_name\":\"Singh" }";  
DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(Data);  

MemoryStream stream = newMemoryStream(Encoding.UTF8.GetBytes(json_data));  
stream.Position = 0;  
Data Detail = (Data Serializer.ReadObject(stream);  
Console.WriteLine(string.Concat("Start", Detail.first_name, "" + Detail.last_name));  
Console.ReadLine();  
.     }  

[DataContract]  
public class Data
{  
[DataMember]  
public string first_name{  
get;  
set;  
}  
[DataMember]  
public string last_name {  
get;  
set;  
}  
} 

Parsing Data Through JSON File’s With C#

We can parse a JSON file using JavaScriptSerializer class.we could use all the data contents of the JSON File’s in our projects in Visual Studio.

Create JSON File in C#

Coding examples are given below here :-

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
namespace DemoModels 
{ 
public class Employee
{ 
public int EmpId 
{ 
get; 
set; 
} 
public string first_name
{ 
get; 
set; 
} 
public string last_name
{ 
get; 
set; 
} 
public string designation
{ 
get; 
set; 
} 
} 
}

Output of the program :-

[ 
{ 
"EmpId": 1, 
"first_name": "Danny", 
"last_name": "decosta", 
"designation": "Clerk"
}, 
{ 
"EmpId": 2, 
"first_name": "Rahul", 
"last_name": "Pratap", 
"designation": "Hr"
}, 
{ 
"EmpId": 3, 
"first_name": "Pooja", 
"last_name": "sharma", 
"designation": "typist"
},
{ 
"EmpId": 4, 
"first_name": "Mini", 
"last_name": "Magel", 
"designation": "Developer"
},
]

Now In this tutorial we will use JavaScriptSerializer class  to deserialize JSON from file.

To use JavaScriptSerializer class you must add the reference of System.Web.Extensions.dll into your project.

Now right click on Controller folder, go to add, then controller, click on it and select MVC5 Controller -Empty and name ReadJsonController.

Now the JSON Controller looks like the code I written below :-

Use modify Index Action method :-

using System.Web; 
using System.Web.Mvc; 
using CreatingJsonFile.Models; 
using System.Web.Script.Serialization;

namespace demo.Controllers 
{ 
public class demoController: Controller 
{ 

public ActionResult Index() 
{ 

string file = Server.MapPath("~/Json_Project/data.json"); 

string Json = System.IO.File.ReadAllText(file); 
JavaScriptSerializer ser = new JavaScriptSerializer(); 
var list= ser.Deserialize < List <Employee>> (Json); 
return View(list); 
} 
} 
}


Now right click on Index() method and click on add view, keep view name as index and select List template. Select Person model class and click on add.

So now let’s see the  view is generated and it is compulsory and here's the coding program is given below :-

@model IEnumerable 

Index 

@foreach (var i in Model) { 



} 
@Html.DisplayNameFor(model => model.first_name) 
@Html.DisplayNameFor(model => model.last_name) 
@Html.DisplayNameFor(model => model.designation) 

@Html.DisplayFor(modelItem => item.first_name)
@Html.DisplayFor(modelItem => item.last_name) 
@Html.DisplayFor(modelItem => item.designation) 

Summary
 

Now the ending is came because our Projects is over and Iam expecting that you all have also completed your projects.For this topic,In the past days, my friend John ask me for this question because he is stuck some where in his project.

John I will give you all of your answer in this tutorial.Thanks for asking it because Iam really enjoying it to solve your problems. 

I hope you all also enjoyed like me to create this project...........


                    Other Links 

>>> Web API in C#                                >>> Signals

>>> CRUD/CURD in Django                   >>> Job Opportunities


>>> Currency Detection By Image in Python         
>>> Pandas Tutorials

                                       
>>> Access Network Drive with password in Python   

Reactions

Post a Comment

0 Comments