JSON Serialization and Deserialization

Convert C# objects to JSON and back

Posted by Rodrigo Castro on January 3, 2025

Modern APIs use JSON for data exchange. Here’s how to work with JSON in C#.

πŸ”„ Serialize (Object β†’ JSON)

1
2
3
4
5
using System.Text.Json;

var user = new User { Name = "Alice", Age = 30 };
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json); // {"Name":"Alice","Age":30}

πŸ” Deserialize (JSON β†’ Object)

1
2
3
string json = "{\"Name\":\"Alice\",\"Age\":30}";
var user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user.Name); // Alice

πŸ› οΈ Customizing Serialization

  • Use [JsonPropertyName("custom_name")] to rename fields.
  • Use JsonSerializerOptions for more control.

πŸ—οΈ Newtonsoft.Json

You can also use Newtonsoft.Json, but System.Text.Json is recommended for most new projects.

Next: Integrating with the ChatGPT API!