Introduction
JSON (JavaScript Object Notation) is a lightweight 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.
JSON represents objects in structured text format and data stored in key-value pairs. Many third-party controls like Kendo UI grid supply data from client size to server-side in JSON string format so it is necessary to cast our JSON string to the appropriate object to access data.There are many ways for working with JSON in C# code.
JSON Using Newtonsoft Libraries
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.
JSON using JsonConverter
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.
In the following example, I have used “JsonConvert.DeserializeObject” method to cast my JSONobject to my custom class object. Here JSON key name must match with the class property name and matching is case insensitive.
static void Main(string[] args)
{
stringjsonData = @ "{
'FirstName': 'Jignesh', 'LastName': 'Trivedi'
}
";
var myDetails = JsonConvert.DeserializeObject < MyDetail > (jsonData);
Console.WriteLine(string.Concat("Hi ", myDetails.FirstName, " " + myDetails.LastName));
Console.ReadLine();
}
public class MyDetail
{
public string FirstName {
get;
set;
}
public string LastName {
get;
set;
}
}JSON using JObject.Parse
JObject class has parse method; it parses the JSON string and converts it into a Key-value dictionary object. In the following example, I have used “JObject.Parse” method and retrieved data using key.
string jsonData = @"{
'FirstName':'Jignesh',
'LastName':'Trivedi'
}";
var details = JObject.Parse(jsonData);
Console.WriteLine(string.Concat("Hi ", details["FirstName"], " " + details["LastName"]));
Console.ReadLine();In the following code snippet, we just assign JObject.Parse method output to dynamic object and access value as properties of dynamic object.
string jsonData = @"{
'FirstName':'Jignesh',
'LastName':'Trivedi'
}";
dynamic data = JObject.Parse(jsonData);
Console.WriteLine(string.Concat("Hi ", data.FirstName, " " + data.LastName));
Console.ReadLine();Note. In the above-described method property name or key name is case sensitive; i.e. property name of class must match key of JSON data.
Using Data Contract Json Serializer class
The .NET framework has also provided 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 the following points must be remembered,
- 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 jsonData = "{ \"FirstName\":\"Jignesh\",\"LastName\":\"Trivedi\" }";
DataContractJsonSerializerjsonSerializer = newDataContractJsonSerializer(typeof(MyDetail));
MemoryStream stream = newMemoryStream(Encoding.UTF8.GetBytes(jsonData));
stream.Position = 0;
MyDetaildataContractDetail = (MyDetail) jsonSerializer.ReadObject(stream);
Console.WriteLine(string.Concat("Hi ", dataContractDetail.FirstName, " " + dataContractDetail.LastName));
Console.ReadLine();
}
[DataContract]
public class MyDetail
{
[DataMember]
public string FirstName {
get;
set;
}
[DataMember]
public string LastName {
get;
set;
}
}Output

Summary
Using the above-described method we can parse JSON in C# code and extract value from this object.
Read more articles on JSON.


QAwithoutDotnetPosted Nov 27, 2023, 9:31 AM EST
Hi @jignesh, i am facing same issue, using the specflow, can you pls share your email id pls
Ramesh REddyPosted Jun 10, 2022, 12:57 PM EDT
Hi Jignesh i need this object {"DTO": json} with class or model how can i implemented in c# can you please help me on this
Rikam PalkarTOP 100Posted May 22, 2020, 4:21 PM EDT
Newsoft is best library for JSON serilizer and De-Serializer. I've been using them for 4 years. They even have same library for Java.
AttiePosted Feb 19, 2018, 12:47 AM EST
Hi Jagnesh, I have a form with button "Select All Emails". Now the problem I have if I click the button it will display all emails in that "ContactEmail" field from the database, if there is no email created it will show "NULL". Now what I want is not to show anything if the field is null (no email created). Below my controller code; public JsonResult GetAllUser(EmployeeModel objModelMail, string to) { List Recyclers = new List(); using (WasteRecyclersEntities db = new WasteRecyclersEntities()) { var query = from q in db.Recyclers select q.ContactEmail; return new JsonResult { Data = query.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
Mahmudul HassanPosted Dec 17, 2017, 10:26 PM EST
Jignesh i have jason array [{{\"id\":\"1\",\"statusName\":\"Pending\"},{\"id\":\"2\",\"statusName\":\"Pending(do not use)\"},{\"id\":\"3\",\"statusName\":\"Live\"}}] like this..I am not able to parse it.please let me know how can i convert this jason
Mahmudul HassanPosted Dec 17, 2017, 10:23 PM EST
Thnks ..nice one..
paresh sukhiyaPosted Sep 11, 2017, 4:11 AM EDT
Sir i want an example to convert the following json to c# object .Please assist me [email protected]":"http://192.168.0.126:49540/odata/$metadata#Edm.String","value":"Tibetan Thukpa Vegetable Soup"}
Humayun Kabir MamunPosted Apr 16, 2016, 9:48 PM EDT
Nice...
Kumaresh RajalingamPosted Apr 16, 2016, 4:34 AM EDT
Good one
Debasis SahaTOP 100Posted Apr 15, 2016, 10:37 PM EDT
Nice One..
Gowtham KTOP 100Posted Apr 15, 2016, 8:55 PM EDT
Good One, Thanks for sharing:)
Vignesh ManiTOP 100Posted Apr 15, 2016, 12:30 PM EDT
Nice one
Rahul Kumar SaxenaTOP 100Posted Apr 15, 2016, 10:11 AM EDT
Good one
Kuppurasu NagarajTOP 100Posted Apr 15, 2016, 9:13 AM EDT
Nice Sharing..
Pankaj Kumar ChoudharyTOP 100Posted Apr 15, 2016, 6:27 AM EDT
Nice Information Sir.......