How to Use JsonSerializer in C# for JSON Conversion
Use
JsonSerializer.Serialize() to convert C# objects to JSON strings and JsonSerializer.Deserialize() to convert JSON strings back to objects. These methods are part of System.Text.Json namespace and provide fast, easy JSON handling.Syntax
The JsonSerializer class provides two main methods:
Serialize(object value): Converts a C# object to a JSON string.Deserialize<T>(string json): Converts a JSON string back to a C# object of typeT.
Both methods are static and part of the System.Text.Json namespace.
csharp
string jsonString = JsonSerializer.Serialize(objectToConvert); MyClass obj = JsonSerializer.Deserialize<MyClass>(jsonString);
Example
This example shows how to serialize a simple Person object to JSON and then deserialize the JSON back to a Person object.
csharp
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person person = new Person { Name = "Alice", Age = 30 }; // Convert object to JSON string string jsonString = JsonSerializer.Serialize(person); Console.WriteLine("Serialized JSON: " + jsonString); // Convert JSON string back to object Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString); Console.WriteLine($"Deserialized Person: Name={deserializedPerson.Name}, Age={deserializedPerson.Age}"); } }
Output
Serialized JSON: {"Name":"Alice","Age":30}
Deserialized Person: Name=Alice, Age=30
Common Pitfalls
Common mistakes when using JsonSerializer include:
- Not including
using System.Text.Json;which causes methods to be unavailable. - Trying to deserialize JSON into a type that does not match the JSON structure, causing exceptions.
- Ignoring case sensitivity: property names in JSON must match C# property names by default (case-sensitive).
- Not handling null values or missing properties which can cause errors or unexpected results.
To fix case sensitivity, use JsonSerializerOptions with PropertyNameCaseInsensitive = true.
csharp
using System.Text.Json; var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; string json = "{\"name\":\"Bob\", \"age\":25}"; Person p = JsonSerializer.Deserialize<Person>(json, options);
Quick Reference
Here is a quick summary of key JsonSerializer methods and options:
| Method/Option | Description |
|---|---|
| Serialize(object value) | Converts an object to a JSON string. |
| Deserialize | Converts JSON string to an object of type T. |
| JsonSerializerOptions.PropertyNameCaseInsensitive | Allows case-insensitive matching of JSON property names. |
| JsonSerializerOptions.WriteIndented | Formats JSON output with indentation for readability. |
Key Takeaways
Use JsonSerializer.Serialize() to convert objects to JSON strings easily.
Use JsonSerializer.Deserialize() to parse JSON strings back to objects safely.
Include System.Text.Json namespace to access JsonSerializer methods.
Handle case sensitivity with JsonSerializerOptions to avoid deserialization errors.
Use options like WriteIndented for readable JSON output.