Serialize and Deserialize JSON Using C#
In this blog post, we will discuss how to serialize and deserialize JSON data in C# using Newtonsoft.Json
package.
Serialization:
Serialization is the process of converting an object into a stream of bytes so that it can be transmitted over a network or saved in a file. In C#, we can serialize an object into JSON format using the JsonConvert.SerializeObject()
method.
Consider the following Employee class:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
To serialize an object of the Employee class into JSON format, we can use the following code:
Employee emp = new Employee
{
Id = 1,
Name = "John",
Email = "[email protected]"
};
string json = JsonConvert.SerializeObject(emp);
Console.WriteLine(json);
The output of the above code will be:
{"Id":1,"Name":"John","Email":"[email protected]"}
In the above code, we first created an object of the Employee class and initialized its properties. We then used the JsonConvert.SerializeObject()
method to serialize the object into JSON format. Finally, we printed the JSON string to the console.
Deserialization:
Deserialization is the process of converting a stream of bytes into an object. In C#, we can deserialize a JSON string into an object using the JsonConvert.DeserializeObject()
method.
Consider the following JSON string:
string json = @"{
'Id': 1,
'Name': 'John',
'Email': '[email protected]'
}";
To deserialize the above JSON string into an object of the Employee class, we can use the following code:
Employee emp = JsonConvert.DeserializeObject<Employee>(json);
Console.WriteLine(emp.Id);
Console.WriteLine(emp.Name);
Console.WriteLine(emp.Email);
The output of the above code will be:
1
John
[email protected]
In the above code, we used the JsonConvert.DeserializeObject()
method to deserialize the JSON string into an object of the Employee class. We then printed the properties of the object to the console.
Comments (0)