How to Deserialize JSON to Object in C# Easily
In C#, you can deserialize JSON to an object using
System.Text.Json.JsonSerializer.Deserialize<T>. This method converts a JSON string into an instance of the specified class T.Syntax
The basic syntax to deserialize JSON into an object is:
JsonSerializer.Deserialize<T>(jsonString): Converts the JSON stringjsonStringinto an object of typeT.T: The class type you want to convert the JSON into.jsonString: The JSON formatted string.
csharp
T obj = JsonSerializer.Deserialize<T>(jsonString);
Example
This example shows how to convert a JSON string representing a person into a Person object using System.Text.Json.
csharp
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { string json = "{\"Name\":\"Alice\", \"Age\":30}"; Person person = JsonSerializer.Deserialize<Person>(json); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } }
Output
Name: Alice, Age: 30
Common Pitfalls
Common mistakes when deserializing JSON include:
- Not matching property names in the class with JSON keys (case-sensitive by default).
- Forgetting to include
using System.Text.Json;. - Trying to deserialize into a class without a public parameterless constructor or public setters.
- Passing invalid or malformed JSON strings.
To fix property name mismatches, you can use [JsonPropertyName] attribute or configure JsonSerializerOptions to ignore case.
csharp
using System.Text.Json; using System.Text.Json.Serialization; public class Person { [JsonPropertyName("name")] public string Name { get; set; } public int Age { get; set; } } // Usage with case-insensitive option var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; string json = "{\"name\":\"Bob\", \"Age\":25}"; Person person = JsonSerializer.Deserialize<Person>(json, options);
Quick Reference
Tips for deserializing JSON in C#:
- Use
System.Text.Jsonfor built-in, fast JSON handling. - Ensure your class properties match JSON keys or use attributes.
- Use
JsonSerializerOptionsto customize behavior like case sensitivity. - Handle exceptions for invalid JSON with try-catch.
Key Takeaways
Use JsonSerializer.Deserialize(jsonString) to convert JSON to a C# object.
Class property names must match JSON keys or use attributes to map them.
Include System.Text.Json namespace to access JsonSerializer.
Use JsonSerializerOptions to handle case sensitivity and other settings.
Always validate JSON format to avoid runtime errors during deserialization.