The integrated “System.Text.Json” module in C# offers classes and methods for serializing (converting C# objects into JSON) and deserializing (converting JSON back to C# objects) the data.
Example 1: Serializing JSON
The process of transforming a C# object into its corresponding JSON format is known as serializing JSON in C#. This JSON form can be sent over the internet or instantly kept in a document. C# has integrated libraries for JSON serialization and deserialization that may be used to do this. The provided C# example code demonstrates how to use the “System.Text.Json” namespace to serialize a ”Test” object into a JSON string and then display the JSON string in the console.
Let’s dissect the code in detail. First, the “Test” class is defined with two properties: “Title” (a string) and “Price” (an integer). These properties represent the attributes of the “t” object. Inside the “Main” method of the “Program” class, a new instance of the “Test” class is created and assigned to the “t” variable. The “Title” property is set to “Blush” and the “Price” property is set to 3000.
The “JsonSerializer.Serialize()” method is used to convert the “t” object into a JSON-formatted string. This method takes the “t” object as input and returns the JSON string that represents the object. The “s” variable contains the produced JSON string. Finally, the “Console.WriteLine()” method is used to display the JSON string in the console. This JSON string represents the “t” object in a serialized format with the “Title” property being set to “Blush” and the “Price” property being set to 3000.
using System.Text.Json;
public class Test
{
public string Title { get; set; }
public int Price { get; set; }
}
public class Dummy
{
public static void Main()
{
Test t = new Test
{
Title = "Blush",
Price = 3000
}; string s = JsonSerializer.Serialize(t);
Console.WriteLine(s);
}
}
When you run this C# program, it prints the following JSON string in the console. The JSON string consists of key-value pairs that are enclosed in curly braces where the keys are the property names of the “Test” class and the values are the corresponding property values of the “t” object.
Example 2: Deserializing JSON
The act of transforming a JSON (JavaScript Object Notation) text into an instance of a particular class or data structure in C# is known as deserializing JSON in C#. To demonstrate the concept of JSON deserializing, we provided another C# code in the following illustration. This C# code defines two classes, “Dummy” and “Test”, and demonstrates how to deserialize a JSON string into an object of the “Dummy” class using the “System.Text.Json” library.
Starting from the “Dummy” class, it has two properties: “Title” of type “string” and “Price” of type “int”. These properties have both getters and setters which make them accessible for serialization and deserialization. After the “Dummy” class, we define the “Test” class that contains the “Main” method to just start the program.
The “Main” method of the “Test” class starts by declaring a JSON string named “s”. The JSON string represents an object with two properties: “Title” and “Price”. The “JsonSerializer.Deserialize<Dummy>(s)” line is used to convert the JSON string “s” into an instance of the “Dummy” class. It performs the deserialization process by mapping the JSON properties to the properties of the “Dummy” class.
The deserialized “Dummy” object is then stored in the “d” variable. Finally, the program prints out the deserialized “Dummy” object’s properties (Title and Price) using the “Console.WriteLine()” method.
using System.Text.Json;
public class Dummy {
public string Title { get; set; }
public int Price { get; set; }
}
public class Test {
public static void Main() {
string s = "{"Title":"Eyeliner","Price":7600}";
Dummy d = JsonSerializer.Deserialize<Dummy>(s);
Console.WriteLine($"Title: {d.Title}, Price: {d.Price}");
}
}
The program successfully deserializes the JSON string and prints the “Dummy” object’s properties that are extracted from the JSON data. The “Title” property contains the “Eyeliner” value, and the “Price” property has the value of “7600”.
Example 3: Serializing and Deserializing the JSON Data
The provided code demonstrates how to serialize and deserialize the JSON data using the “System.Text.Json” namespace in C#.
Let’s dive into the code starting from its “Data” class. The “Data” class is a simple C# class that represents a data structure that contains two properties: “Subj” (subject) and “Score” (score). These properties are defined with “get” and “set” accessors which allows them to be both read and written and making them accessible for serialization and deserialization.
In the “Main” method, the code demonstrates the JSON serialization. It creates a new instance of the “Data” class named “d” and assigns the values to its “Subj” and “Score” properties. The “Math” and “25” values are assigned to “Subj” and “Score”, respectively.
Next, the JsonSerializer.Serialize() method is called with the “d” object as the argument. This method converts the “Data” object into a JSON-formatted string which is stored in the “ser” variable. Finally, the console is used to print the serialised JSON string to the console. Use the WriteLine() to output the outcome. After serialization, the code demonstrates the JSON deserialization. In this section, it creates a JSON string “js” which contains the information about a different subject and score: “Comp” with a score of 75.
The JsonSerializer.Deserialize<Data>(js) method is then used to deserialize the JSON string into a new instance of the “Data” class named “des”. This method parses the JSON string and creates a “Data” object with the “Subj” property being set to “Comp” and the “Score” property being set to 75. Finally, the deserialized “Data” object is printed to the console using the Console.WriteLine() which shows the subject and score of the deserialized data.
using System.Text.Json;
public class Data {
public string Subj { get; set; }
public int Score { get; set; }
}
public class Test {
public static void Main() {
// Serialization
Data d = new Data
{
Subj = "Math",
Score = 25
};
string ser = JsonSerializer.Serialize(d);
Console.WriteLine("Serialized JSON:");
Console.WriteLine(ser);
Console.WriteLine();
// Deserialization
string js = "{"Subj":"Comp","Score":75}";
Data des = JsonSerializer.Deserialize<Data>(js);
Console.WriteLine("Deserialized Object:");
Console.WriteLine($"Subj: {des.Subj}, Score: {des.Score}");
}
}
Upon running the code, you should see the following output. The serialized JSON output shows that the “Data” object with the “Subj” being set to “Math” and the “Score” being set to 25 is converted into a JSON string: “{“Subj”:”Math”,”Score”:25}”. The deserialized object output shows that the JSON string “{“Subj”:”Comp”,”Score”:75}” is successfully converted back into a “Data” object with the “Subj” being set to “Comp” and the “Score” being set to 75.
Conclusion
It’s critical to remember that the “System.Text.Json” package offers several options and settings for serialization and deserialization including the custom converters, handling the null data, and disabling the particular attributes. When utilizing more intricate JSON formats, knowing these choices might be helpful.