JSON to C# Class

Infer C# classes from a JSON sample.

About JSON to C# Class

Generate C# classes for System.Text.Json from a JSON sample. Paste JSON and classes with typed properties and JsonPropertyName attributes appear as you type.

How to use

  1. Paste JSON, or load a .json file (up to 5 MB).
  2. Optionally change the root class name (default Root). It must start with a letter or underscore and contain only letters, digits and underscores.
  3. The C# code updates as you type. Copy it, or Download it as a .cs file.

What it does

JSON C#
string string
integer long
other number double
boolean bool
null, or mixed types JsonElement
array List<T>
nested object a named class, RootAddress
null in some items, or key missing from some items T?
  • Properties are PascalCase with { get; set; }. Every property whose key differs from its name, including id → Id, gets [JsonPropertyName("key")], so the class round-trips without a naming policy.
  • Nested classes are listed before the class that uses them. using lines cover only what the classes need: System.Text.Json.Serialization always, System.Collections.Generic for lists and System.Text.Json for JsonElement.
  • A key that matches its class name gets a Value suffix, because a member may not share the name of its enclosing type.

Example

{ "id": 1, "userName": "Ada", "tags": ["admin"] }
using System.Collections.Generic;
using System.Text.Json.Serialization;

public class Root
{
    [JsonPropertyName("id")]
    public long Id { get; set; }

    [JsonPropertyName("userName")]
    public string UserName { get; set; }

    [JsonPropertyName("tags")]
    public List<string> Tags { get; set; }
}

Privacy

Inference runs in the page. No request is made and nothing is stored.

Frequently asked questions

What is the difference between JsonPropertyName and JsonProperty in C#?
JsonPropertyName belongs to System.Text.Json (System.Text.Json.Serialization) and JsonProperty to Newtonsoft.Json. Both set the JSON key for a property; use the one that matches the serialiser your project calls, since each ignores the other.
How do I deserialize JSON to a C# class?
Call JsonSerializer.Deserialize<Root>(text) from System.Text.Json. Property names are matched case-sensitively by default, so either add JsonPropertyName attributes or pass JsonSerializerOptions with PropertyNameCaseInsensitive = true.
What does the ? after a type mean in C#?
For a value type such as long or bool it makes a Nullable<T> that can hold null. For a reference type such as string it is a nullable annotation that tells the compiler, with nullable reference types enabled, that null is an expected value.
Why is a JSON number mapped to long instead of int?
A JSON integer has no declared size, and IDs and timestamps regularly exceed the int limit of about 2.1 billion. long covers them safely; change a property to int when you know the values stay small.