Let’s go through JSON serialization and deserialization in C# β€” a common way to convert objects to JSON strings and vice versa.


πŸ“Œ 1. What is JSON Serialization?

  • Serialization converts a C# object into a JSON string.

  • Useful for storing, transmitting, or exchanging data between applications.

πŸ“Œ 2. What is JSON Deserialization?

  • Deserialization converts a JSON string back into a C# object.

  • Makes it easy to read data from APIs, files, or databases.


πŸ“Œ 3. Using System.Text.Json (Modern Way)

  • Available in .NET Core 3.0+ / .NET 5+

  • Namespace: System.Text.Json

  • Classes: JsonSerializer

Example Class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

πŸ“Œ 4. Serialization Example

using System.Text.Json;
 
Person person = new Person { Name = "Alice", Age = 25 };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);

Output:

{"Name":"Alice","Age":25}
  • Converts the object into JSON string

πŸ“Œ 5. Deserialization Example

string jsonString = "{\"Name\":\"Bob\",\"Age\":30}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"{person.Name} is {person.Age} years old.");

Output:

Bob is 30 years old.
  • Converts JSON string back into a C# object

πŸ“Œ 6. Serialization Options

var options = new JsonSerializerOptions
{
    WriteIndented = true, // Makes JSON readable with line breaks
};
 
string prettyJson = JsonSerializer.Serialize(person, options);
Console.WriteLine(prettyJson);

Output:

{
  "Name": "Alice",
  "Age": 25
}

πŸ“Œ 7. Using Newtonsoft.Json (Popular Alternative)

  • Install NuGet package: Newtonsoft.Json

  • Namespace: Newtonsoft.Json

using Newtonsoft.Json;
 
Person person = new Person { Name = "Charlie", Age = 22 };
 
// Serialize
string json = JsonConvert.SerializeObject(person);
 
// Deserialize
Person p = JsonConvert.DeserializeObject<Person>(json);
  • More feature-rich, supports advanced scenarios

πŸ“Œ 8. Working with Collections

List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 25 },
    new Person { Name = "Bob", Age = 30 }
};
 
string json = JsonSerializer.Serialize(people);
var deserializedPeople = JsonSerializer.Deserialize<List<Person>>(json);
  • Works with arrays, lists, dictionaries as well

πŸ“Œ 9. Summary Table

FeatureDescription
SerializationObject β†’ JSON string
DeserializationJSON string β†’ Object
System.Text.JsonModern, built-in
Newtonsoft.JsonFeature-rich, widely used
CollectionsSupports arrays, lists, dictionaries
OptionsFormatting (WriteIndented), ignoring nulls, etc.

βœ… Tip:

  • Use System.Text.Json for modern .NET applications

  • Use Newtonsoft.Json if you need advanced features like polymorphic serialization, flexible converters, or legacy support