Juarez Júnior
Posted on October 17, 2024
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
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}");
}
}
}
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
Posted on October 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 26, 2024