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!