Introduction to JSON Parser in C#
JSON (JavaScript Object Notation) parse is language-independent which is a lightweight data-interchanging format, self-describing, and easy to understand. JSON parser is an alternative to XML it represents objects in structural text format and the data stored in key-value pairs. The extension of JSON filename is .json. The classes of JSON allowed to serialize the objects into JSON text and also to de-serialize JSON text to objects there is built-in support of UTF-8.
Syntax:
Let’s see the syntax for JSON (JavaScript Object Notation) as follows,
- Jobject.Parse() method is an object class method and this method is used to parse the JSON string into the objects of C#. Based on the key value it parses the data of string and then it retrieves the data by using the key values. For the parse method the syntax is as follows,
Jobject.Parse(jsonStringName);
- Another method to parsing the JSON String using JsonConvert.DeserializeObject() which belongs to the JsonConvert class. Let’s see the syntax below,
JsonConvert.DeserilizeObject<CustomClassName>(JsonStringName);
- To parsing the JSON String using JavaScriptSerialize(). Deserialize() method, this method is only applied to the latest versions of .NET, let’s see the syntax below
JavaScriptSerializer(). Deserialize<CustomClassName>(jsonString);
How JSON parser works in C#?
JSON (JavaScript Object Notation) is a lightweight data-interchanging format and it is easy to write and read by humans and is parsed which generated by machines. It provides high-performance, less memory space allocation. There are many third-party controls to supply data from Client-side to Server-side in JSON string format and it is essential to cast the JSON string to a suitable object to access the data, third-party controls like Kendo UI grid, and so on. In this, there is UTF-8 built-in support.
Jobject.Parse() method is an object class method and this method is used to parse the JSON string into the objects of C#. Based on the key value it parses the data of string, finally, it retrieves the data by using the key values. Let’s see the JSON parsing format and working flow below,
{
string jsonString = @"{
'user_FirstName':'Peter',
'user_LastName':'Paul'
}";
By using the JSON parsing method we can convert and retrieve as follows,
var getResult = JObject.Parse(jsonString);
This way we can retrieve the data.
Another method to parsing the JSON String using JsonConvert.DeserializeObject() which belongs to the JsonConvert class the method called JsonConvert.DeserializeObject() used to convert the JSON string to the C# object. Those objects are created by the JSON string. The format used for this method is as follows,
JsonConvert.DeserilizeObject<CustomClassName>(JsonStringName);
To retrieve the result of this method we can use like this way, to create a class UserDetails with attributes First_Name and Last_Name, to input the data in JSON format like below
var get_jsonString = @"{'First_Name': 'Peter', 'Last_Name': 'Paul'}";
To convert the data by this way as follows,
var result = JsonConvert.DeserializeObject < UserDetails > (get_jsonString);
To parsing the JSON String using JavaScriptSerialize(). Deserialize() method, this method is only applied to the later versions of .NET, this method will not be applicable for earlier versions for that purpose we can use the first two methods to convert the JSON string to C# objects. The format used for this method is as follows,
JavaScriptSerializer().Deserialize<CustomClassName>(jsonString);
To create the class with UserDetails as follows,
class UserDetails
{
public string userName { get; set; }
public int userAge { get; set; }
}
To input the details of the user for the conversion from JSON to c# objects as follows,
var input_json = @"{""name"":""Peter Paul"",""age"":49}";
To convert the json to c# objects by using serializer() method below as follows,
var resultObject = new JavaScriptSerializer().Deserialize<UserDetails>(input_json);
.NET framework supports the classes for de-serializing and serializing to JSON, by using the one we use with DataContractJsonSerializer. By using the code below we can de-serialize the JSON objects, for using the method we need to some procedures as follows,
The application must have the reference of the System.Runtime.Serialization library.
The entire class should have DataContract and the attributes must have DataMember attributes.
[DataContract]
public class USerDetails
{
[DataMember]
public string First_Name {
get; set;
}
[DataMember]
public string Last_Name {
get; set;
}
}
- For serializing and de-serializing we need to use WriteObject method to serialize an object and to use ReadObject method to de-serialize the JSON objects.
string get_json = "{ \"First_Name\":\"Smith\",\"LastName\":\"Rio\" }";
DataContractJsonSerializerjsonSerializer = newDataContractJsonSerializer(typeof(USerDetails));
Json.NET is the best framework for the working environment for. NET. There are many benefits and features of JSON is as follows,
- It is the flexible conversion of JSON serializer between .NET objects and JSON
- There will be the manual writing and reading JSON of LINQ to JSON
- It works faster than .NET and it has built-in JSON serializers with high-performance data.
- Easy to read JSON and write indented.
- The conversion between JSON and XML is easy.
Examples
Program #1
Jobject.Parse() method is an object class method and this method is used to parse the JSON string into the objects of C#. Based on the key value it parses the data of string, finally, it retrieves the data by using the key values. Let’s see the JSON parsing implementation below,
using System;
using Newtonsoft.Json.Linq;
namespace JSONParsing
{
public class Parsing
{
public static void Main(string[] args)
{
string jsonString = @"{
'user_FirstName':'Peter',
'user_LastName':'Paul'
}";
//Using the JSON-parse method here
var getResult = JObject.Parse(jsonString);
Console.WriteLine("\n\tUsing JSON-Parse Method");
Console.WriteLine(string.Concat("\n\tDisplaying User First and Last Name: ", getResult["user_FirstName"], " " + getResult["user_LastName"], "."));
}
}
}
Output:
Program #2
To parsing the JSON String using JsonConvert.DeserializeObject() which belongs to the JsonConvert class the method called JsonConvert.DeserializeObject() used to convert the JSON string to the C# object. Those objects are created by the JSON string.
using System;
using Newtonsoft.Json;
namespace JSONParse_Program
{
public class UserDetails
{
public string First_Name
{
get; set;
}
public string Last_Name
{
get; set;
}
}
public class Parsing
{
public static void Main(string[] args)
{
var get_jsonString = @"{'First_Name': 'Peter', 'Last_Name': 'Paul'}";
//Use of the method
var result = JsonConvert.DeserializeObject < UserDetails > (get_jsonString);
Console.WriteLine("JSON-Parse Method\n");
Console.WriteLine(string.Concat("\nDisplaying First and Last Name, ", result.First_Name, " " + result.Last_Name, "."));
}
}
}
Output:
Conclusion
In this article, I have explained the usage of JSON parser for example, by using those methods we can parse the JSON in the C# program and also extract values.
Recommended Articles
This is a guide to JSON Parser in C#. Here we discuss the Introduction, syntax, How JSON parser work in C#? and examples respectively. You may also have a look at the following articles to learn more –
6 Online Courses | 18 Hands-on Project | 90+ Hours | Verifiable Certificate of Completion
4.6
View Course
Related Courses