Deserialize JSON to C# Classes with System.Text.Json
Turn a JSON sample into C# classes and deserialize it with System.Text.Json or Newtonsoft. Tested attributes, case rules, records, decimal money and the real exception messages.
On this page ⌄
- The sample and the generated classes
- System.Text.Json vs Newtonsoft.Json: what differs
- The exceptions you will actually see
- Production fixes to the generated code
- Frequently asked questions
- How JSON types map to C# types
- Nullable fields, snake_case keys and PascalCase properties
- From a C# class back to JSON
- When you have no class: JsonNode and JsonObject
- Quick answers
- Tested
The hard part of calling a JSON API from .NET is rarely the JsonSerializer.Deserialize<T> line. It is the T: a set of classes whose names, types and nullability match a payload you only have one sample of. This guide takes one realistic order response, generates the classes, deserializes it with both System.Text.Json and Newtonsoft.Json, and then breaks it on purpose so you can see which exception each mistake produces.
The sample and the generated classes
{
"orderId": "ORD-9821",
"total": 149.99,
"isPaid": true,
"createdAt": "2026-05-12T14:30:00Z",
"coupon": null,
"customer": { "id": 7, "name": "Bob Smith" },
"items": [
{ "sku": "WIDGET-A", "qty": 2, "price": 49.99 },
{ "sku": "WIDGET-B", "qty": 1, "price": 50.01, "note": "gift" }
]
}
Pasting that into the JSON to C# Class converter with root name OrderResponse and the System.Text.Json attribute option produces this (copied from the tool's output; the Customer class is shortened here):
using System.Text.Json.Serialization;
using System.Collections.Generic;
public class OrderResponse
{
[JsonPropertyName("orderId")]
public string OrderId { get; set; }
[JsonPropertyName("total")]
public double Total { get; set; }
[JsonPropertyName("isPaid")]
public bool IsPaid { get; set; }
[JsonPropertyName("createdAt")]
public string CreatedAt { get; set; }
[JsonPropertyName("coupon")]
public object? Coupon { get; set; }
[JsonPropertyName("customer")]
public Customer Customer { get; set; }
[JsonPropertyName("items")]
public List<Items> Items { get; set; }
}
public class Customer { /* Id (int), Name (string) */ }
public class Items
{
[JsonPropertyName("sku")] public string Sku { get; set; }
[JsonPropertyName("qty")] public int Qty { get; set; }
[JsonPropertyName("price")] public double Price { get; set; }
[JsonPropertyName("note")] public string? Note { get; set; }
}
Three things in that output are worth knowing before you paste it into a project:
notebecamestring?because it appears in only one of the two array elements. The generator merges every element of an array, so a field missing from some elements is treated as optional. A field missing from all of them is invisible to it.couponwasnullin the sample, so the type is unknowable and falls back toobject?. Replace it by hand once you know the real type (string?ordecimal?).createdAtisstringandtotalisdouble, because JSON has no date or decimal type. Both are fixed below.
The output was compiled and run (details in the Tested note). With <Nullable>enable</Nullable> the non-nullable string properties raise warning CS8618 ("Non-nullable property 'OrderId' must contain a non-null value when exiting constructor"), six of them for this sample. That is a warning, not an error, but fix it with = string.Empty;, the required modifier, or ? before you commit.
Deserializing it:
var order = JsonSerializer.Deserialize<OrderResponse>(json)!;
Console.WriteLine($"{order.OrderId} {order.Customer.Name} {order.Items[1].Sku} note={order.Items[1].Note}");
// ORD-9821 Bob Smith WIDGET-B note=gift
System.Text.Json vs Newtonsoft.Json: what differs
| Behavior | System.Text.Json | Newtonsoft.Json |
|---|---|---|
| Rename attribute | [JsonPropertyName("orderId")] | [JsonProperty("orderId")] |
| Property name matching | Case-sensitive by default | Case-insensitive by default |
| Unknown JSON members | Ignored | Ignored (error only with MissingMemberHandling.Error) |
"49.99" into double | Throws unless NumberHandling.AllowReadingFromString | Converts silently |
| Trailing comma | Throws | Accepted |
The case rule is the one that bites. Both of these ran as written:
class Plain { public string OrderId { get; set; } = ""; public double Total { get; set; } }
JsonSerializer.Deserialize<Plain>("{\"orderId\":\"A1\",\"total\":5}");
// OrderId = "" , Total = 0 (no error, nothing bound)
var opt = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
JsonSerializer.Deserialize<Plain>("{\"orderId\":\"A1\",\"total\":5}", opt);
// OrderId = "A1", Total = 5
The first call silently returns an object full of defaults. If your payload is camelCase and your properties are PascalCase, either keep the generated attributes, set PropertyNameCaseInsensitive = true, or construct the options with JsonSerializerDefaults.Web (this was confirmed to bind {"orderId":"W1"} to OrderId and write camelCase back out). Newtonsoft matched {"orderid":"zz"} to OrderId with no options at all.
The exceptions you will actually see
Each row below is the real Message from the code that caused it. System.Text.Json messages end with | LineNumber: 0 | BytePositionInLine: N., which are trimmed here.
| JSON | Target | Serializer | Message |
|---|---|---|---|
{"qty":2.5} | int | System.Text.Json | The JSON value could not be converted to System.Int32. Path: $.qty |
{"qty":null} | int | System.Text.Json | The JSON value could not be converted to System.Int32. Path: $.qty |
{"total":"49.99"} | double | System.Text.Json | The JSON value could not be converted to System.Double. Path: $.total |
{"at":"yesterday"} | DateTimeOffset | System.Text.Json | The JSON value could not be converted to System.DateTimeOffset. Path: $.at |
{"qty":1} | List<Qty> | System.Text.Json | The JSON value could not be converted to System.Collections.Generic.List`1[Qty]. Path: $ |
[{"qty":1}] | Qty | System.Text.Json | The JSON value could not be converted to Qty. Path: $ |
{"id":1} | ctor BadCtor(int idd) | System.Text.Json | Each parameter in the deserialization constructor on type 'BadCtor' must bind to an object property or field on deserialization. |
{} | required string Name | System.Text.Json | JSON deserialization for type 'Req' was missing required properties including: 'Name'. |
{"qty":1,} | any | System.Text.Json | The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options. |
| empty string | any | System.Text.Json | The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. |
{"qty":2.5} | int | Newtonsoft | Input string '2.5' is not a valid integer. Path 'qty', line 1, position 10. |
{"qty":"abc"} | int | Newtonsoft | Could not convert string to integer: abc. Path 'qty', line 1, position 12. |
{"qty":null} | int | Newtonsoft | Error converting value {null} to type 'System.Int32'. Path 'qty', line 1, position 11. |
{"qty":1} | List<Qty> | Newtonsoft | Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[Qty]' because the type requires a JSON array ...` |
How to fix each:
- Could not be converted to System.Int32 with
2.5: the sample had whole numbers, the real data does not. Usedoubleordecimal. - Same message with
null: a value type cannot hold null. Declareint?. - A number sent as a string: either change the property to
stringand parse it, or setNumberHandling = JsonNumberHandling.AllowReadingFromString. With that option"49.99"read as49.99. - Object where a list was expected (and the reverse): the endpoint returns
{...}for one result and[...]for many, or wraps the list in{"data":[...]}. Look at the first character of the response, then deserialize into the wrapper class orList<T>accordingly. - Each parameter in the deserialization constructor must bind: every constructor parameter needs a property whose name matches (case-insensitively) and whose type matches.
BadCtor(int idd)against a propertyIdfails; rename the parameter toid. This is the usual error when you switch a class to a primary constructor or record and a parameter name drifts from the property. - Missing required properties: a
requiredmember (C# 11) with no JSON value throws in System.Text.Json. Make it optional or fix the payload.
Production fixes to the generated code
Money as decimal. Generators emit double for any number with a fraction. In C#, 0.1 + 0.2 printed 0.30000000000000004 for double and 0.3 for decimal. Change Total and Price to decimal; System.Text.Json reads 49.99 straight into it. Summing two item prices of 1.10 and 2.20 as decimal gave exactly 3.30.
Dates as DateTimeOffset. "2026-05-12T14:30:00Z" deserialized into a DateTimeOffset property as 2026-05-12T14:30:00.0000000+00:00 with offset 00:00:00. An unparseable value such as "yesterday" throws the DateTimeOffset message in the table, not a null.
Records for read-only responses. This deserialized the whole sample (with decimal and DateTimeOffset) in one shot, using case-insensitive options:
public record Customer(int Id, string Name);
public record Item(string Sku, decimal Price);
public record OrderRec(string OrderId, decimal Total, bool IsPaid, DateTimeOffset CreatedAt,
string? Coupon, Customer Customer, List<Item> Items);
var rec = JsonSerializer.Deserialize<OrderRec>(json, opt)!; // rec.Items.Count == 2
Record parameters must match the JSON names (see the constructor-binding error above). Properties in the JSON that the record does not declare, such as qty, are skipped.
Rename the plural class. The tool named the array element class Items after the key. Rename it to OrderItem; the attribute-driven mapping keeps working because it goes by the JSON key, not the class name.
Array roots. JsonSerializer.Deserialize<List<Item>>("[{...},{...}]") returns a List<Item> directly; there is no need for a wrapper class when the root is an array.
Frequently asked questions
How do I paste JSON as classes in Visual Studio? Copy the JSON, place the cursor in a .cs file, and use Edit > Paste Special > Paste JSON As Classes. Not tested: the IDE feature. For System.Text.Json attributes, or to avoid opening the IDE, use the online converter.
How do I deserialize a JSON array to List<T>? JsonSerializer.Deserialize<List<T>>(json). If the array is nested under a key, deserialize the wrapper class and read its List<T> property.
Should I use System.Text.Json or Newtonsoft? Both ran the whole example. System.Text.Json is stricter by default (case, numbers in strings, trailing commas), which surfaces bad assumptions early; Newtonsoft is more forgiving. Pick one per project and keep the attributes consistent.
Why is my property null or zero with no exception? Most often the name does not match and System.Text.Json is case-sensitive. See the Plain example above.
If the sample itself does not parse, check it in the JSON Formatter first. For the same exercise in Go see Go structs from JSON. You can validate a payload first in the JSON Formatter.
How JSON types map to C# types
JSON has six value kinds, so every choice of C# type is a decision about what your data will really contain. A second sample, deserialized with System.Text.Json on .NET 10, shows the choices that matter:
{"id":9007199254740993,"name":"Ada","score":4.5,"price":19.99,"active":true,
"born":"1990-04-12T08:30:00Z","ref":"3f2504e0-4f89-41d3-9a0c-0305e82c3301",
"status":"shipped","middle_name":null,"tags":["a","b"],
"scores":{"math":90,"art":75},"address":{"city":"Lahore"}}
| JSON value | C# type that worked | Result printed by the test program |
|---|---|---|
number without a fraction, larger than int.MaxValue | long | 9007199254740993 (kept exactly) |
same number into int | int | The JSON value could not be converted to System.Int32. Path: $.id |
| number with a fraction | double or decimal | 4.5, and 19.99 as decimal |
true / false | bool | True |
| ISO 8601 string | DateTimeOffset | 1990-04-12T08:30:00.0000000+00:00 |
| UUID string | Guid | 3f2504e0-4f89-41d3-9a0c-0305e82c3301 |
null | string? | null |
| array | List<string> | a,b |
| object with fixed keys | a class | Address.City = Lahore |
| object with dynamic keys | Dictionary<string, int> | math=90,art=75 |
Two rules follow. Pick long for identifiers you do not control, since int fails the moment a value passes 2,147,483,647. And model a JSON object as a Dictionary<string, T> when its keys are data (names, dates, ids) rather than field names, because a class cannot have a property for every possible key.
Nullable fields, snake_case keys and PascalCase properties
Microsoft's serialization guide notes that by default the casing of JSON names matches the .NET names and that you can customize it. In practice there are three separate tools:
[JsonPropertyName("middle_name")]on a single property: a PascalCase C# name (MiddleName) for any JSON key. This is what the converter on this site emits, and it works whatever the casing of the key.- A naming policy on the options, for the whole model:
JsonNamingPolicy.CamelCase, orJsonNamingPolicy.SnakeCaseLower(available in the .NET 10 run used here). Run on a plain class,{ OrderId = "A1", Total = 5m, Note = null }serialized as{"OrderId":"A1","Total":5,"Note":null}by default,{"orderId":"A1","total":5,"note":null}withCamelCaseand{"order_id":"A1","total":5,"note":null}withSnakeCaseLower. - A nullable annotation (
string?,int?,decimal?) for any key that can benullor absent. Astring?property received"middle_name":nullasnull; a plainintthrows onnull, as the exceptions table above shows.
From a C# class back to JSON
Going the other way is one call. These outputs were captured from the same test program:
JsonSerializer.Serialize(person);
// {"id":9007199254740993,"name":"Ada",...,"middle_name":null,"tags":["a","b"],...}
var options = new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
JsonSerializer.Serialize(person, options); // indented, and middle_name is left out
The Microsoft serialization guide notes that the output is minified by default and that WriteIndented pretty-prints it. Enums are written as numbers unless you ask otherwise: new { Status = Status.Shipped } gave {"Status":1}, and adding new JsonStringEnumConverter() to options.Converters gave {"Status":"Shipped"}. Reuse one JsonSerializerOptions instance instead of creating one per call; the same guide recommends it.
For Newtonsoft.Json, JsonConvert.SerializeObject(plain) produced {"OrderId":"A1","Total":5.0,"Note":null}. Note the 5.0: Newtonsoft writes a decimal with its fractional digit where System.Text.Json wrote 5.
When you have no class: JsonNode and JsonObject
Sometimes the shape is unknown, or you only need one value. Microsoft's DOM guide describes JsonNode (a mutable tree, with JsonObject and JsonArray derived from it) for exactly this. The test program parsed the sample without any class:
var node = JsonNode.Parse(json)!;
node["name"]!.GetValue<string>(); // Ada
node["address"]!["city"]; // Lahore
node["tags"]![0]; // a
node["nope"] is null; // True, a missing key returns null instead of throwing
var obj = new JsonObject { ["name"] = "Ada", ["tags"] = new JsonArray("x", "y"), ["n"] = 3 };
obj["extra"] = true;
obj.ToJsonString(); // {"name":"Ada","tags":["x","y"],"n":3,"extra":true}
Choose a class when the shape is stable and you want compile-time checks; choose JsonNode for one-off reads, for payloads whose shape varies, and for editing JSON in place. The same page notes that JsonDocument is read-only and faster, but it must be disposed. Newtonsoft's equivalent, JObject.Parse(json)["address"]["city"], returned Lahore as well.
Quick answers
- How do I convert JSON to a C# model? Take a representative sample, generate the classes with the JSON to C# Class converter, then fix the three things a sample cannot tell you: money fields to
decimal, timestamps toDateTimeOffset, and nullable fields to?types. - What is the difference between a class and a record for JSON? Both deserialize; records bind through the constructor, so parameter names must match the JSON keys, as the
BadCtorrow above shows. - How do I check the JSON before I model it? Run it through the JSON Validator or the JSON Formatter; a trailing comma or a single quote fails there before it fails in your code.
- Same exercise in another language? See TypeScript types from JSON and the Go struct guide.
Sources used in this section: Microsoft Learn, How to serialize JSON in C#, and Microsoft Learn, How to use a JSON DOM in System.Text.Json.
Tested
Run on 2026-11-02 and again on 2026-11-06: .NET SDK 10.0.302 targeting net10.0 (System.Text.Json built in), Newtonsoft.Json 13.0.4, Windows 11.
- Class output generated by the xerobit json-to-csharp-class module and compiled with
dotnet build(6 CS8618 warnings, no errors). Every exception message and result in the sections above the type-mapping heading was captured fromdotnet runon 2026-11-02. - The type-mapping, naming-policy, serialization, enum,
JsonNodeandJObjectexamples were rebuilt as a console project and re-run on 2026-11-06; the printed outputs match the page, including theInt32exception for9007199254740993. - The Microsoft Learn pages "How to serialize JSON in C#" and "How to use a JSON DOM in System.Text.Json" were read on 2026-11-06.
- Message wording can differ slightly in older .NET versions.
- Not tested: Visual Studio's Paste JSON As Classes, ASP.NET Core model binding, and .NET versions other than 10.
Keep reading
Related tools
JSON to C# Class Converter
Paste JSON to generate C# classes with inferred types, PascalCase naming and optional serialization attributes.
JSON Formatter
Format, validate, and beautify JSON online. 100% client-side, your data never leaves your browser.
HTML Viewer & Formatter
Paste HTML and see it rendered live in a sandboxed preview. Format and beautify messy markup, inline CSS and JS. Desktop, tablet and mobile widths.
JSON Viewer
Explore JSON as a collapsible tree. Paste JSON and navigate nested structures with expand/collapse and JSONPath copy.
Written by Mian Ali Khalid. More guides in Data & Format.