JSON with System.Text.Json
What is JSON?
JSON is a plain-text format for data, used by almost every web API. It uses objects { }, arrays [ ], text, numbers and true/false/null.
json
{
"name": "Ana",
"age": 25,
"skills": ["C#", "SQL"]
}
Serialize: Object to JSON
csharp
using System.Text.Json;
var person = new Person("Ana", 25, ["C#", "SQL"]);
string json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
// {"Name":"Ana","Age":25,"Skills":["C#","SQL"]}
record Person(string Name, int Age, List<string> Skills);
Deserialize: JSON to Object
csharp
string input = """{"Name":"Raj","Age":31,"Skills":["Azure"]}""";
Person? raj = JsonSerializer.Deserialize<Person>(input);
Console.WriteLine(raj?.Name); // Raj
Options: Pretty Print and camelCase
csharp
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true // helps when reading
};
Console.WriteLine(JsonSerializer.Serialize(person, options));
Create the options once: Store
JsonSerializerOptions in a static readonly field and reuse it. Creating it on every call is slow. ASP.NET Core already uses camelCase and case-insensitive reading for you.
Control Names and Hide Properties
csharp
using System.Text.Json.Serialization;
class Product
{
[JsonPropertyName("product_name")]
public string Name { get; set; } = "";
public decimal Price { get; set; }
[JsonIgnore]
public string InternalNote { get; set; } = "";
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Description { get; set; }
}
Lists and Nested Objects
csharp
record Address(string City, string Country);
record Customer(string Name, Address Address, List<string> Tags);
var customers = new List<Customer>
{
new("Ana", new("Paris", "FR"), ["vip"]),
new("Raj", new("Delhi", "IN"), [])
};
string text = JsonSerializer.Serialize(customers, options);
var back = JsonSerializer.Deserialize<List<Customer>>(text, options);
Save and Load a JSON File
csharp
await File.WriteAllTextAsync("customers.json", text);
string fileText = await File.ReadAllTextAsync("customers.json");
var loaded = JsonSerializer.Deserialize<List<Customer>>(fileText, options) ?? [];
Read Part of Unknown JSON
csharp
using var doc = JsonDocument.Parse("""{"user":{"id":7,"emails":["a@x.com","b@x.com"]}}""");
int id = doc.RootElement.GetProperty("user").GetProperty("id").GetInt32();
foreach (var email in doc.RootElement.GetProperty("user").GetProperty("emails").EnumerateArray())
Console.WriteLine(email.GetString());
Call a Web API and Read JSON
csharp
using var client = new HttpClient();
var todo = await client.GetFromJsonAsync<Todo>("https://jsonplaceholder.typicode.com/todos/1");
Console.WriteLine(todo?.Title);
record Todo(int UserId, int Id, string Title, bool Completed);
Tip:
GetFromJsonAsync and PostAsJsonAsync from System.Net.Http.Json combine the request and JSON conversion in one call.
Conclusion
JsonSerializer converts objects and JSON in both directions. Use options for naming, attributes for special cases and JsonDocument when the shape is unknown.
Quick Summary: Serialize = object to text, Deserialize = text to object, options for camelCase and indentation.

