How to use it
- Paste a JSON sample. Use a realistic one: the more items an array holds, the better optional keys are detected.
- Choose classes or records, and whether to add [JsonPropertyName] attributes.
- Copy the code into a .cs file. The top-level type is Root; rename it to suit your domain.
How it works
The sample is read into a shape: each key with every type seen there. All objects of one array are merged into one class, so a key present in only some of them becomes nullable.
- Property names are PascalCase built from the key: order_id → OrderId, first-name → FirstName, 2fa → N2fa.
- A property may not share its class’s name, so a key item inside class Item becomes ItemValue.
- Class names come from keys too: items holds a List
- , customer becomes Customer. Root comes first, nested classes after it.
- With a top-level array, a comment names the type to deserialize, such as List
.
Worked example
{"items":[{"sku":"A","note":null,"qty":1},{"sku":"B","note":"x"}]} as classes without attributes gives:
using System.Collections.Generic;
public class Root
{
public List<Item> Items { get; set; } = new();
}
public class Item
{
public string Sku { get; set; } = "";
public string? Note { get; set; }
public long? Qty { get; set; }
}
note is null once, so it is string?. qty is missing from the second item, so it is long?.
Tips
- Check numbers the sample got lucky with: a price of 24 in every item gives long, though real data may hold 24.99.
- Deserialize with
JsonSerializer.Deserialize<Root>(json); for a top-level array use the type named in the comment. - For other languages, see JSON to Java, JSON to TypeScript and JSON to Go.