Skip to content
DevTinyTools

JSON to C# Class Generator

Turn a JSON response into C# classes that deserialise on the first try: nullable annotations computed from every record, initialisers that keep the build warning-free, and [JsonPropertyName] wherever C# naming disagrees with the wire.

Runs entirely in your browser — your JSON is never uploaded.

0 chars
0 lines

Free generation covers up to 1,000,000 characters per document — what Pro adds. The JSON you paste never leaves the tab; inference runs in your browser.

How to generate C# classes from JSON

  1. Paste a JSON object or array or load the example: two orders whose item lists disagree, which is exactly where single-sample generators get it wrong.
  2. Name the root class and the namespace The root name becomes the first class and the file name. The namespace is optional — leave it blank for a snippet you paste into an existing project.
  3. Choose the serialiser style System.Text.Json attributes are on by default. Turn them off if you already configure PropertyNameCaseInsensitive or use a naming policy.
  4. Copy or download the .cs file Every class is in one file, all top-level, so it compiles as-is in any project that targets .NET 6 or newer.

Nullable reference types: the switch that decides whether this compiles cleanly

C# has two kinds of null, and JSON only has one. A reference type (string, List<T>, your own classes) is nullable by nature; a value type (long, bool) is not. Since C# 8 the compiler can track that difference for you — but only inside a nullable annotations context, which is why the generated file starts with #nullable enable whenever a ? is actually emitted.

  • Key in every record → non-nullable. public string Email { get; set; } = string.Empty; — dereference it freely, and the serialiser fails loudly if the API ever stops sending it.
  • Key missing or null → `?`. public string? CouponCode { get; set; } or public long? Quantity { get; set; }. The compiler now forces a null check before use, which is the only reason the annotation is worth writing.
  • Initialisers keep the build green. Without them, every non-nullable reference property produces CS8618 and a project with warnings-as-errors refuses to build. The values are overwritten during deserialisation, so they cost nothing at runtime.

This is the part most converters skip. They emit public string CouponCode { get; set; } for a key that was null half the time, the project compiles with 40 warnings, and the first missing field throws a NullReferenceException three layers away from the JSON. The types here come from sampling every array element, so “optional” is a fact about your data rather than a guess.

Names: PascalCase in C#, snake_case on the wire

C# convention says CouponCode; the API says coupon_code. Both names have to survive, and System.Text.Json is case-sensitive by default — even total will not bind to Total without help. So the generator annotates every property whose exact spelling differs:

  • [JsonPropertyName("coupon_code")] above public string CouponCode.
  • Keys that start with a digit get a prefix (2fa_enabled → Field2faEnabled), because a C# identifier cannot start with a number.
  • Two keys that collapse onto the same C# name (user_id and userId) are deduplicated as UserId / UserId2, each keeping its own annotation — silently dropping one field is the alternative, and it loses data.

One file, every class top-level

C# allows many classes per file, so unlike the Java output there is no need to nest them: nested objects and array elements become sibling classes named after their path — Order → OrderCustomer → OrderItems. Arrays map to List<T> rather than T[], because that is what System.Text.Json and most C# code expect to iterate.

Integers become long, not int: 32 bits overflow on timestamps in milliseconds and on totals in cents. Narrowing a field you know is small is a safe manual edit. Floats become double, and mixed number/string fields become object — money should not be a double at all, which the precision guide explains with the decimal argument.

None of this is better than the sample it was inferred from: one record makes every key look required. The reasoning is laid out in your sample is not a schema, and it holds for C# as much as for TypeScript. For the parts specific to System.Text.Json — what required adds over #nullable enable, and why a mixed-type field becomes a JsonElement — read nullable annotations, CS8618 and JsonElement.

DevTinyTools Pro

The free generator handles the payloads most people paste by hand. Pro raises the document cap and unlocks every other tool on the site:

  • 10,000,000-character documents, roughly 10 MB of JSON
  • The same Pro licence unlocks every tool on the site — TypeScript, Go, Java, schemas, batch ZIP export
  • Priority fixes — generation bugs move to the front of the queue

Pro is $29 one-time — a lifetime licence, sold through Lemon Squeezy as merchant of record, so VAT and sales tax are handled for you. Pro is a licence key — there is still no account. Buy DevTinyTools Pro, then activate it below and the higher limits unlock in this browser.

Frequently asked questions

Why does the output start with #nullable enable?
Because the optionality inferred from your sample is worthless unless the compiler enforces it. With nullable annotations on, string? means the key may be absent or null, and the compiler warns you when you dereference it without checking. Without that switch, string? is a comment: every reference type quietly accepts null and you find out at runtime.
Why are some numbers long? and others long?
A whole number that every sampled record carried is a plain long. If any record omitted the key or sent null, the property becomes long? — a Nullable<long>, which is how C# represents an absent value type without boxing. The generator decides from every array element, not just the first, because a single record makes everything look required.
Why is [JsonPropertyName] on almost every property?
System.Text.Json matches property names case-sensitively by default, so a JSON key of total will not bind to a C# property named Total without help. Since the C# convention is PascalCase and JSON is usually camelCase or snake_case, the annotation is emitted wherever the exact spelling differs. Turn the checkbox off if you configure PropertyNameCaseInsensitive or use a naming policy that already handles it.
Why do properties have = string.Empty; or = new();?
A non-nullable reference property that nobody initialises triggers compiler warning CS8618, and warnings-as-errors turns that into a failed build. Required strings get string.Empty, required lists and nested classes get new(); required value types need nothing because their default is valid. The file is then warning-free without any behaviour change — System.Text.Json overwrites the values during deserialisation.
Does it work with Newtonsoft.Json instead of System.Text.Json?
Yes. Newtonsoft honours [JsonPropertyName] from System.Text.Json, but if you drop the annotation, add [JsonProperty] with the same key instead — Newtonsoft is case-insensitive by default, so plain camelCase properties often bind without any attribute at all.
Can I get records instead of classes?
Not yet. Records with positional parameters need a constructor signature that matches the JSON exactly, and a missing optional key then becomes a constructor argument problem rather than a property one. Classes with get; set; deserialise reliably under both serialisers, and converting a small class to a record afterwards is a one-line edit.
What happens when a key is sometimes a string and sometimes a number?
It becomes object, which System.Text.Json deserialises into a JsonElement — you then read it with GetString() or GetInt64() where you consume it. C# has no union types, and picking one of the two would make deserialisation fail on the other shape.
Is my JSON uploaded anywhere?
No. Parsing, inference and code generation all run in this tab. The file picker uses FileReader, and no network request is made while generating — you can verify that in your browser's network panel.
JSON RepairFix broken JSON from an assistant or a config file: fences, comments, single quotes, trailing commas, Python literals and truncated tails — with every change reported.JSON Formatter & ValidatorPretty-print JSON with 2 or 4 space indentation, check the syntax and copy or download the result.JSON ValidatorCheck whether a JSON document is valid and see exactly where the parser stopped.JSON MinifierStrip whitespace from JSON and see how many bytes the minified output saves.JSON Diff CheckerCompare two documents and list every added, removed and changed value with its path.JSON Escape & UnescapeTurn raw text into a JSON string value, or decode backslashes and \u escapes back into readable text.JSON to CSV ConverterTurn an array of JSON objects into a CSV file you can open in a spreadsheet.JSON to TypeScript GeneratorGenerate TypeScript interfaces from a JSON sample, with optional properties and unions inferred from every array element.JSON to Go Struct GeneratorGenerate Go structs from a JSON sample, with json tags, int64 or float64 widths, pointers for null fields and omitempty for optional keys.CSV to JSON ConverterConvert CSV to JSON with RFC 4180 parsing, delimiter detection, dotted headers unflattened into nested objects and numbers converted only when they round-trip exactly.JSON to Java POJO GeneratorGenerate Java classes from JSON: primitives for required values, boxed types for optional and nullable ones, @JsonProperty for renamed keys and nested static classes.JSON to YAML Converter (and back)Convert JSON to YAML or YAML to JSON in both directions, with multi-document support, error line numbers and YAML 1.2 typing rules.JSON to Python Class GeneratorGenerate Pydantic v2 models or dataclasses from JSON, with snake_case fields, Optional where a key is missing or null, and keyword keys renamed safely.JSON to JSON Schema GeneratorTurn a JSON sample into a draft 2020-12 schema: required keys, nullable unions and nested $defs.