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
| Feature | Description |
|---|---|
| Serialization | Object β JSON string |
| Deserialization | JSON string β Object |
| System.Text.Json | Modern, built-in |
| Newtonsoft.Json | Feature-rich, widely used |
| Collections | Supports arrays, lists, dictionaries |
| Options | Formatting (WriteIndented), ignoring nulls, etc. |
β Tip:
-
Use
System.Text.Jsonfor modern .NET applications -
Use
Newtonsoft.Jsonif you need advanced features like polymorphic serialization, flexible converters, or legacy support