DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Object Serialization and Deserialization with Newtonsoft.Json

The Newtonsoft.Json library, also known as Json.NET, is widely used to convert C# objects to JSON and vice-versa. This makes communication between services and data storage in a lightweight, widely supported format much easier. In this example, we will see how to serialize a C# object to JSON and then deserialize the JSON back into an object.

Libraries:
To use the Newtonsoft.Json library, install the NuGet package in your project:

Install-Package Newtonsoft.Json
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Newtonsoft.Json;
using System;

namespace NewtonsoftJsonExample
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating a sample object
            Product product = new Product { Id = 1, Name = "Laptop", Price = 1500.99m };

            // Serializing the object to JSON
            string json = JsonConvert.SerializeObject(product);
            Console.WriteLine("Serialized object: " + json);

            // Deserializing the JSON back to an object
            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
            Console.WriteLine("Deserialized object: ");
            Console.WriteLine($"Id: {deserializedProduct.Id}, Name: {deserializedProduct.Name}, Price: {deserializedProduct.Price}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:
In this example, we create a Product class with three properties: Id, Name, and Price. In the Main method, we instantiate an object of this class and serialize it into a JSON string using the JsonConvert.SerializeObject() method. The resulting JSON is printed to the console. Then, we use the JsonConvert.DeserializeObject() method to convert the JSON back into a Product object. Finally, the data from the deserialized object is displayed in the console.

Conclusion:
The Newtonsoft.Json is an essential tool for handling JSON data in C#. It allows you to serialize and deserialize objects in a simple and fast manner, saving time when developing applications that need to interact with APIs or store data.

Source code: GitHub

Top comments (0)