JSON to C# Classes: JsonPropertyName and Nullable Reference Types

Last updated: · 9 min read

To work safely with an API response in C#, you first turn it into classes. System.Text.Json matches property names case-sensitively by default, so a JSON key called html_url does not bind to a property called HtmlUrl on its own. The JSON to C# Class Converter writes classes with PascalCase properties from a sample you paste, puts a [JsonPropertyName] attribute carrying the JSON name on every property, and marks fields that can be null as T?. This guide covers the tool's typing and naming rules, what the initialisers it emits under #nullable enable are for, and where a single sample can mislead you. The output shown is the tool's real result, and the conversion runs in your browser.

Formula

Rules:
1. Every JSON object becomes a public class. The root class name is converted to PascalCase from what you type (user → User).
2. Property names are PascalCase: html_url → HtmlUrl, USER_ID → UserId. Each property is preceded by [JsonPropertyName("key")], with the key spelled as in the JSON.
3. Numbers: no decimal point or exponent and fits in 32 bits → int; fits in 64 bits → long; written like 4.0, 2.5 or 1e3, or too large for long → double.
4. Strings become string, true/false becomes bool and arrays become List<T>. Every nested object is a separate class, named after the property and not singularised (repos → Repos, List<Repos>).
5. A field that is null somewhere, or missing from some objects in an array, is marked T?: int?, bool?, string?.
6. Non-nullable reference types get an initialiser: = ""; for string, = new(); for lists and objects.
7. Fields that were only ever null and mixed types become object?; an empty array becomes List<object>.
8. The file starts with #nullable enable and the using lines it needs. If the root value is not an object, a comment line at the top shows how to read it.

Input (root class name: user):
{"id":7,"html_url":"https://example.com/u/7","created_at":"2024-05-01T10:00:00Z","followers":3000000000,"rating":4.0,"profile":{"display_name":"Ada","bio":null},"repos":[{"repo_id":1,"private":false},{"repo_id":2,"license":"MIT"}]}

Output:
#nullable enable

using System.Collections.Generic;
using System.Text.Json.Serialization;

public class User
{
    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("html_url")]
    public string HtmlUrl { get; set; } = "";

    [JsonPropertyName("created_at")]
    public string CreatedAt { get; set; } = "";

    [JsonPropertyName("followers")]
    public long Followers { get; set; }

    [JsonPropertyName("rating")]
    public double Rating { get; set; }

    [JsonPropertyName("profile")]
    public Profile Profile { get; set; } = new();

    [JsonPropertyName("repos")]
    public List<Repos> Repos { get; set; } = new();
}

public class Profile
{
    [JsonPropertyName("display_name")]
    public string DisplayName { get; set; } = "";

    [JsonPropertyName("bio")]
    public object? Bio { get; set; }
}

public class Repos
{
    [JsonPropertyName("repo_id")]
    public int RepoId { get; set; }

    [JsonPropertyName("private")]
    public bool? Private { get; set; }

    [JsonPropertyName("license")]
    public string? License { get; set; }
}

This is type inference, not a formula. The tool parses the JSON, works out a type for every value and merges the objects of an array field by field. JSON (RFC 8259) does not distinguish integers from decimals, so the tool looks at how a number is written: System.Text.Json throws a JsonException when asked to read a number spelled 4.0 into an int property. The initialisers (= ""; and = new();) are there so the compiler does not warn that a non-nullable property is left unassigned; they also mean a field absent from the JSON ends up as an empty string or an empty list rather than null.

What the inputs mean

JSON
The sample the classes are inferred from. Paste a real response; if you put several different records into one array, fields that can be null or are sometimes absent are marked far more accurately.
Root class name
The name of the outermost class. Root is used when the box is empty. Whatever you type is converted to PascalCase: my data → MyData. A name starting with a digit gets a leading underscore.

Worked example: Generating classes from a user response

  1. The root class name is user, so the class is declared as public class User. The file opens with #nullable enable and two using lines: using System.Collections.Generic; and using System.Text.Json.Serialization;
  2. The id key becomes the property Id, and the attribute carries the JSON name: [JsonPropertyName("id")] followed by public int Id { get; set; }
  3. html_url and created_at are text. As non-nullable strings they are initialised with an empty string: public string HtmlUrl { get; set; } = ""; The tool does not interpret strings, so created_at stays a string even though it is an RFC 3339 timestamp. Change the type to DateTimeOffset if you want a date.
  4. followers is 3000000000, above the int maximum of 2147483647, so it becomes long: public long Followers { get; set; } rating is written 4.0 in the sample, so it becomes double: public double Rating { get; set; }
  5. profile is a nested object; a Profile class is generated and the property is initialised with an empty instance: public Profile Profile { get; set; } = new(); The repos array becomes public List<Repos> Repos { get; set; } = new();
  6. bio is only ever null in this sample, so its type is unknown: public object? Bio { get; set; } If it is really text, change it to string?.
  7. The two objects in repos share repo_id; private appears only in the first and license only in the second, so both are marked nullable: public bool? Private { get; set; } and public string? License { get; set; }
  8. A root array: for [{"id":1,"nick":null},{"id":2,"nick":"ada"}] the first line of the output is a comment: // The JSON root is not an object; read it with: JsonSerializer.Deserialize<List<Root>>(json) The nick field, null in one element, becomes public string? Nick { get; set; }
  9. Where the type cannot be known: for {"tags":[],"mixed":[1,"x"],"huge":9223372036854775808} the empty array and the mixed array both become List<object> (public List<object> Tags { get; set; } = new();), and 9223372036854775808, which does not fit in a long, is written as public double Huge { get; set; } At that magnitude a double cannot hold most integers exactly.

Result: The output consists of three classes: User, Profile and Repos. Before using it, give Bio its real type, use DateTimeOffset for CreatedAt and rename Repos to Repo. To read the data, JsonSerializer.Deserialize<User>(json) is all you need.

🟪 JSON to C# Class Converter

Free, no sign-up; your data stays in your browser.

Open the calculator →

How to read the result

Treat the generated classes as a first draft. Nullable reference types are purely a compile-time feature; string and string? are the same type at run time. With default settings, an explicit null in the JSON is therefore assigned without complaint to a string property you declared non-nullable. From .NET 9 on, turning on JsonSerializerOptions.RespectNullableAnnotations makes that case throw a JsonException. A missing field is a separate matter: a property the JSON does not mention keeps its initial value and no error is raised. If a field must be present, add the required modifier or the [JsonRequired] attribute; a missing field is then reported with a JsonException. Value types behave differently: null arriving for an int property fails, which is why the tool makes numbers that were null somewhere int?. Properties typed object? hold a JsonElement at run time.

Common mistakes

  • Deleting the attributes and expecting names to match on their own. System.Text.Json is case-sensitive by default; html_url does not match HtmlUrl and the property silently stays empty.
  • Relying on a string property never being null. Nullability annotations belong to compile time; with default settings a JSON null is assigned to a string property, and the first use may throw a NullReferenceException.
  • Reading the initialisers as "this field is required". = ""; and = new(); only silence a compiler warning; nothing fails when the field is absent. Use required or [JsonRequired] to enforce presence.
  • Leaving money amounts as double. The tool writes double for every decimal number, and binary floating point cannot represent values such as 0.1 exactly. Change amount fields to decimal by hand.
  • Trusting classes generated from a single record. With one element in an array no field becomes T?; the tool can only notice that a field is sometimes missing when it sees several records.
  • Leaving object? and List<object> lines as they are. They only say that null was all the tool saw, or that the array was empty or mixed; find out the real type and write it in.
  • Reading integers that do not fit in a long as double. Most integers above 9223372036854775807 cannot be held exactly in a double; make such fields decimal or string.

Frequently asked questions

What does [JsonPropertyName] do, and do I need it?

It sets the property's name in the JSON. It applies to both reading and writing and takes precedence over any naming policy. A single naming policy can replace the attributes: if every key is snake_case, setting JsonSerializerOptions.PropertyNamingPolicy to JsonNamingPolicy.SnakeCaseLower (.NET 8 and later) does the same job. The tool writes the attribute on every property so the classes work even when key styles are inconsistent.

string vs string?: what is the difference?

Under #nullable enable, string declares a reference that is not meant to be null, and string? one that may be. The compiler issues warnings based on those declarations; at run time both are System.String. The tool uses string? for fields that were null somewhere or absent from some records.

Are a missing field and a null field the same thing?

They differ in JSON, but in C# both usually show up as null, and the tool writes T? in either case. When reading, the difference is this: a missing field leaves the property at its initial value, while an explicit null assigns null to it.

Should a number be int, long or double?

The tool goes by the sample value: an integer that fits in 32 bits becomes int, a larger one long, and a number written with a decimal point or exponent double. For fields that can grow, such as IDs, long is the safer choice even when the sample value is small.

Can I use these classes with Newtonsoft.Json?

The classes themselves work, but [JsonPropertyName] belongs to System.Text.Json only. Newtonsoft.Json uses its own [JsonProperty] attribute for the same purpose, so the attributes and the using line have to be changed accordingly.

Can I use a record instead of a class?

Yes. System.Text.Json supports record types; you can write public record in place of public class, or use init instead of set. As long as the properties and their attributes stay as they are, the mapping does not change.

Is my JSON sent to a server?

No. The conversion runs in your browser. It is still good practice to strip access tokens and personal data from a response before pasting it anywhere.

The result is not exact or binding and is for information only; it is not an official document and cannot be used in official procedures. Confirm it with the competent authority or a professional before acting; no liability is accepted for losses arising from its use.

Sources

Choose your cookie preference to continue

Records the site needs to work (theme, language, favourites) stay in your browser.

This site is free and funded by ads.

With your consent, Google Analytics cookies measure visits and Google AdSense cookies are used to show ads; the data is processed on Google servers abroad.

If you reject, the site works just the same.

Cookie Policy · KVKK notice