Serialization and Deserialization with JSON in C#

Shahzad Aslam
1 min readFeb 3, 2024

JSON Serialization and Deserialization in C# involve converting objects to and from JSON format. The JsonSerializer class, available in the System.Text.Json namespace, is commonly used for this purpose. Here’s an example demonstrating JSON serialization and deserialization in C#.

Serialization and Deserialization with JSON in C# : Example

using System;
using System.Text.Json;
// Sample class to be serialized
[Serializable]
public class Fruit
{
public string Name { get; set; }
public int Price { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
// Create an instance of the class
Fruit fruit = new Fruit { Name = "Apple", Price = 26 };
// Serialize the object to JSON
string json = SerializeObjectToJson(fruit);
// Display the serialized JSON
Console.WriteLine("Serialized JSON:");
Console.WriteLine(json);
// Deserialize the JSON to an object
Fruit deserializedPerson = DeserializeJsonToObject(json);
// Display the deserialized object
Console.WriteLine("Deserialized Object:");
Console.WriteLine($"Name: {deserializedPerson.Name}, Price: {deserializedPerson.Price}");
}
// Serialize an object to JSON
static string SerializeObjectToJson(Fruit obj)
{
return JsonSerializer.Serialize(obj);
}
// Deserialize JSON to an object
static Fruit DeserializeJsonToObject(string json)
{
return JsonSerializer.Deserialize<Fruit>(json);
}
}

Thanks for read.

For more useful tutorials please visit the site: C-Sharp Tutorial and also if you find useful to this article please clap and follow the author by hitting below button.

--

--

Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.