You call a partner API from a .NET service and get back a block of JSON with nested objects, arrays and a few null values. To work with it safely you want real C# types, not a JsonDocument you walk by hand or a dynamic that fails at runtime. Writing those classes by hand is tedious, and it is easy to get a property name or a nullable marker wrong.
This guide explains how System.Text.Json maps JSON to C# types, how to choose between classes and records, and how to generate a first draft of the model from a sample payload. It also covers the places where a generated model needs a human review before it goes into production code.
How System.Text.Json maps JSON to C#
System.Text.Json is the serializer built into .NET since .NET Core 3.0. When you call JsonSerializer.Deserialize<T>(json), it reads each JSON property and looks for a matching public property on T. Three rules decide whether the match succeeds:
- Names are case-sensitive by default. A JSON key
orderIddoes not fill a C# propertyOrderIdunless you add[JsonPropertyName("orderId")], passJsonSerializerOptionswithPropertyNameCaseInsensitive = true, or useJsonSerializerDefaults.Web. - Unknown JSON keys are ignored. Extra fields in the payload do not cause an error; they are simply skipped.
- Missing JSON keys leave the property at its default. A missing
longbecomes0, a missingstringstays at whatever the initializer set, and a missing reference type isnullunless you initialise it.
Type mapping is mostly predictable:
| JSON value | Typical C# type |
|---|---|
"text" |
string |
42 |
int or long |
4.7 |
double or decimal |
true / false |
bool |
{ ... } |
a nested class or record |
[ ... ] |
List<T> or T[] |
null |
a nullable type such as string? or long? |
Dates arrive as strings in JSON. System.Text.Json can read ISO 8601 strings like 2024-03-18T09:12:44Z straight into DateTime or DateTimeOffset, but only if you declare the property with that type.
Classes or records?
Both work with System.Text.Json. A class with { get; set; } properties is the classic choice: easy to modify after deserialization and familiar to every C# developer. A positional record is shorter, immutable and gives you value equality for free, which suits data you read but do not change, such as API responses or messages from a queue. Records deserialize through their constructor, so the parameter names must match the property names, and attributes need the property: target to reach the generated property.
Generate C# types from a JSON sample
Our JSON to C# Class tool builds the classes from a sample in your browser, so the payload never leaves your device.
- Open JSON to C# Class and paste a real response into the JSON sample box, use Open file to load a
.jsonfile, or click Load sample to see how it works. - Set Root type name to something meaningful, such as
CustomerorInvoiceResponse. - Enter a Namespace (optional), for example
Billing.Api.Models. Leave it empty for a file without a namespace block. - Pick Declare as: class with properties or positional record.
- Keep [JsonPropertyName] attributes switched on if your JSON uses camelCase or snake_case keys. Each property then carries the exact JSON key.
- Review the C# classes output, then Copy it or Download it as a
.csfile.
The generator merges identical object shapes into one type, names nested types from their keys (an orders array becomes List<Order>), and uses long for whole numbers and double for decimals. Non-nullable strings and collections get = string.Empty; or = new(); initialisers so the compiler's nullable warnings stay quiet. A key that is null in the sample, or missing from some array items, becomes a nullable type such as string?.
Deserializing the result
With the generated class in place, deserializing takes one call:
using System.Text.Json;
using Billing.Api.Models;
string json = await File.ReadAllTextAsync("customer.json");
Customer? customer = JsonSerializer.Deserialize<Customer>(json);
if (customer is null)
{
throw new InvalidDataException("The response body was empty or null.");
}
Console.WriteLine($"{customer.Name} has {customer.Orders.Count} orders");
If you already use HttpClient, the System.Net.Http.Json extensions do the same in one step and use web defaults (camelCase, case-insensitive):
Customer? customer = await httpClient.GetFromJsonAsync<Customer>("customers/4821");
When you prefer not to put attributes on every property, drop them and configure the serializer once:
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
Customer? customer = JsonSerializer.Deserialize<Customer>(json, options);
Reuse a single JsonSerializerOptions instance rather than creating one per call; the serializer caches metadata on it.
Other ways to get C# classes from JSON
- Visual Studio's Paste Special. In Visual Studio, copy JSON, then use Edit → Paste Special → Paste JSON as Classes. It is quick and offline, but it does not add
[JsonPropertyName]attributes and names nested types generically, so expect some tidying. - Write them by hand. For three or four properties this is often fastest, and you choose precise types from the start.
- Generate from a schema. If the API publishes an OpenAPI or JSON Schema document, a schema-based generator is more reliable than any single sample, because the schema states which fields are required. If you only have samples, you can build a schema first with the JSON Schema Generator and review it.
- Skip typed models. For a one-off script,
JsonDocumentorJsonNodelets you read a value or two without any classes. Typed models pay off once the data travels through more than one method.
Review checklist before you commit the model
A sample shows one moment of an API, not its contract. Check these points by hand.
Replace object? with the real type
If a key is null in every sample, the generator cannot know what it normally holds and writes object?. Change it to string?, long? or a nested type based on the API documentation, or paste a second sample in which the value is filled.
Choose number types on purpose
long and double are safe defaults. Use decimal for money, because binary floating point cannot represent values such as 0.1 exactly. If a field happens to be a whole number in your sample (say a price of 12), it may be generated as long even though other responses contain decimals, so check prices, rates and totals.
Use real date types
Timestamps come out as string. Change them to DateTimeOffset when the value includes a time zone offset or Z, and to DateOnly (from .NET 7 onward) for plain dates, so you do not parse strings throughout your code.
Watch for invalid JSON
A trailing comma or single quotes stop the generator with an error. Run the payload through the JSON Validator or tidy it in the JSON Formatter to locate the problem line first.
Keep one model per contract
If you generate models for several services, the same concept (an address, a money amount) may appear with slightly different shapes. Decide whether to share one type or keep them separate per API, rather than merging them by accident.
For the TypeScript side of the same API, the guide on generating TypeScript types from JSON covers the equivalent workflow, and JSON to Java Class does the same for Java services.
Frequently asked questions
Why are my C# properties null after deserializing JSON?
Usually the names do not match: System.Text.Json is case-sensitive by default, so orderId will not fill OrderId. Add [JsonPropertyName] attributes or use JsonSerializerDefaults.Web, which enables case-insensitive matching.
Should I use a record or a class for JSON data?
Use a record for data you only read, such as API responses, because it is concise and immutable. Use a class when you need to change values after deserializing or when a framework expects settable properties.
Does System.Text.Json fail on extra JSON fields?
No. Unknown properties are ignored by default. From .NET 8 you can opt into stricter behaviour with JsonUnmappedMemberHandling.Disallow if you want unexpected fields to raise an error.
How do I deserialize a JSON array at the top level?
Deserialize into a collection of your type, for example JsonSerializer.Deserialize<List<Customer>>(json). When the root of your sample is an array, the generator adds a comment showing the matching call.
Is it safe to paste production JSON into the generator?
The tool runs in your browser and does not upload the sample. Even so, it is good practice to replace personal data, keys and tokens with placeholder values before sharing a payload anywhere.