TechieClues TechieClues
Updated date Mar 28, 2024
This blog post explains how to serialize and deserialize JSON data in C# using the built-in Newtonsoft.Json package. It covers the basics of serialization and deserialization and provides sample code for both operations.
  • 5.4k
  • 0
  • 0

 

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.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!