How to Generate C# Classes from JSON
Deserializing JSON in C# needs classes that match the payload. Generating them from a sample saves the tedious part and gets the attributes right. Here's what the output looks like and why.
From JSON to classes
Each JSON object becomes a class, nested objects become their own classes, and keys become PascalCase properties:
{ "id": 1, "user_name": "Ada" }
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class Root
{
public int Id { get; set; }
[JsonPropertyName("user_name")]
public string UserName { get; set; }
}
Why the [JsonPropertyName] attribute
C# convention is PascalCase properties, but JSON keys are often camelCase or snake_case. When the property name doesn't match the key, a [JsonPropertyName("...")] attribute is added so System.Text.Json maps the value correctly. Keys that already match (like id → Id, matched case-insensitively) don't need one.
Nullable types
Value types that are optional or null in the sample become nullable — int?, bool?, double?. Reference types like string, List<T>, and nested classes are already nullable, so they're left as-is. A field with no inferable type falls back to object.
Using Newtonsoft.Json instead
The generated attribute targets System.Text.Json. For Newtonsoft.Json, swap [JsonPropertyName("x")] for [JsonProperty("x")] — the class shapes are otherwise identical.
Related
Generating types for another language? See JSON to TypeScript and JSON to Go.
Try it
Paste a JSON response and get C# classes instantly — everything runs in your browser, nothing uploaded.