JSON Parser in C#

PHPz
PHPzOriginal
2024-09-03 15:33:301050browse

JSON (JavaScript Object Notation) parse is language-independent, 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 is stored in key-value pairs. The extension of the JSON filename is .json. The JSON classes allow to serialize the objects into JSON text and de-serialize JSON text to objects; there has 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 string’s data and then retrieves the data using the key values. For the parse method, the syntax is as follows,
Jobject.Parse(jsonStringName);
  • Another method for parsing the JSON String is using JsonConvert.DeserializeObject(), which belongs to the JsonConvert class. Let’s see the syntax below,
JsonConvert.DeserilizeObject<CustomClassName>(JsonStringName);
  • Parse the JSON String using JavaScriptSerialize(). De-serialize () method, this method is only applied to the latest versions of .NET; let’s see the syntax below
JavaScriptSerializer(). Deserialize<CustomClassName>(jsonString);

How does JSON parser work 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 and generated by machines. It provides high performance and 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 string’s data and retrieves the data 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 for parsing the JSON String is using JsonConvert.DeserializeObject(), which belongs to the JsonConvert class, the method called JsonConvert.DeserializeObject() converts the JSON string to the C# object. The JSON string creates those objects. The format used for this method is as follows,

JsonConvert.DeserilizeObject<CustomClassName>(JsonStringName);

Create a class called UserDetails with the attributes First_Name and Last_Name to input the data in the JSON format shown below to receive the results of this function.

var get_jsonString = @"{'First_Name': 'Peter', 'Last_Name': 'Paul'}";

To convert the data this way as follows,

var result = JsonConvert.DeserializeObject < UserDetails > (get_jsonString);

To parse the JSON String using JavaScriptSerialize(). De-serialize () method is only applied to the later versions of .NET; this method will not apply to 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 the 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 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 do 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;
}
}
  • We must use the WriteObject method to serialize an object and the 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. NET. There are many benefits and features of JSON, 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 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 the string and retrieves the data 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:

JSON Parser in C#

Program #2

To parse the JSON String using JsonConvert.DeserializeObject(), which belongs to the JsonConvert class, the method called JsonConvert.DeserializeObject() converts the JSON string to the C# object. The JSON string creates those objects.

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:

JSON Parser in C#

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 extract values.

The above is the detailed content of JSON Parser in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# DataTable FilterNext article:C# DataTable Filter