JSON to C# Class

The JSON to C# Class Generator converts a JSON sample into C# class definitions with auto-implemented properties and System.Text.Json or Newtonsoft.Json attributes. Use it to generate typed models for ASP.NET Core controllers, HttpClient response deserialisation, Azure Function payloads, and Blazor API data binding.

S. Siddiqui

Edited by

S. SiddiquiFounder & Editor-in-Chief
Sources:MDN Web DocsW3CIETFUpdated Jun 2026

What Is the JSON to C# Class Generator?

The JSON to C# Class Generator analyses a JSON sample and produces C# class definitions with auto-implemented properties, ready for use with System.Text.Json (the built-in .NET JSON library since .NET Core 3.0) or Newtonsoft.Json (Json.NET). Each JSON object becomes a C# class with public auto-properties, and each JSON key becomes a property with the appropriate C# type. Optional [JsonPropertyName] attributes are added for System.Text.Json, or [JsonProperty] for Newtonsoft.Json, to preserve exact JSON key name mapping.

C# is a statically typed language that requires class or record definitions before you can work with structured data in a type-safe way. Without a typed class, developers must use dynamic or JsonElement for JSON access — both of which are verbose and lose compile-time safety. With a generated class, JsonSerializer.Deserialize<MyClass>(jsonString) produces a fully typed C# object in one line, giving you IntelliSense autocomplete, compile-time type checking, and refactoring support across the entire codebase.

According to the Microsoft documentation for System.Text.Json, the recommended approach for JSON serialisation in .NET is to define plain C# classes or records with public properties that match the JSON structure. This generator produces those classes from a real JSON sample, eliminating manual transcription of property names and types.

This generator is used by ASP.NET Core developers typing API request and response models, .NET developers integrating third-party REST APIs, Azure Function developers processing JSON event payloads, and Blazor developers defining data models for API calls.

How to Use the JSON to C# Class Generator

  1. Paste your JSON sample. The input should be a representative JSON object or array. Include null values and all possible fields to produce the most accurate class definition. Fields with null values generate nullable types (string? in C# 8+ with nullable reference types enabled, or Nullable<int> for value types).
  2. Enter a class name. Enter a PascalCase class name — for example User, Product, or ApiResponse. Nested objects generate additional classes named from the property key in PascalCase.
  3. Choose your JSON library. Select System.Text.Json (default, built-in to .NET) to add [JsonPropertyName("keyName")] attributes. Select Newtonsoft.Json to add [JsonProperty("keyName")] attributes instead.
  4. Review type mappings. JSON strings become string. JSON integers become int or long. JSON floats become double. JSON booleans become bool. JSON null values produce nullable types. JSON arrays become List<T> or T[].
  5. Copy and use. Paste the generated classes into your C# project. Add using System.Text.Json; and deserialise: var user = JsonSerializer.Deserialize<User>(jsonString);

Why Use This Tool

A JSON object with 15 fields, 3 nested objects, and 2 list properties requires 15 property declarations, appropriate type annotations, and JSON attribute decorations — roughly 50 lines of C# class code when written with full property names and attributes. Writing this manually from an API sample is tedious. This tool generates the complete class structure in seconds from a real JSON sample.

ASP.NET Core REST API developers

ASP.NET Core uses System.Text.Json by default for deserialising request bodies and serialising response objects. A developer adding a new controller action that accepts a complex request body needs a C# class matching the expected JSON structure. This generator produces that class from a sample request payload, giving the developer a typed request model that the framework will validate and populate automatically via model binding.

.NET developers consuming third-party APIs

Any .NET service calling a third-party REST API — GitHub, Stripe, SendGrid, Twilio — needs C# classes matching the API's JSON response shapes. This generator produces those classes from a real API response captured in Postman or from the API documentation sample, eliminating the need to transcribe dozens of property names and types manually.

Azure Function developers processing event payloads

Azure Functions triggered by Service Bus, Event Grid, or HTTP endpoints receive JSON payloads as their input. Strongly typing these payloads with C# classes — deserialised with JsonSerializer.Deserialize — makes function code more readable, easier to test, and safer to refactor than working with raw string or JObject inputs. This generator produces the typed classes from a real event payload sample.

Blazor and MAUI developers calling APIs

Blazor WebAssembly and MAUI applications call REST APIs using HttpClient and deserialise JSON responses into C# objects. Developers define model classes in a shared project that is referenced by both the front-end and back-end. This generator produces those shared model classes from API response samples, ensuring front-end data binding uses the same strongly typed models as back-end business logic.

Real-World Use Cases

ASP.NET Core developer integrating a payment gateway

A back-end developer builds a payment processing service in ASP.NET Core that integrates with Stripe's API. Stripe returns complex nested JSON for payment intents, customers, and charge objects. The developer captures real Stripe test response payloads from the Stripe CLI, pastes each into this generator, and produces C# classes for PaymentIntent, Customer, PaymentMethod, and their nested types. The classes are placed in a Models/Stripe/ directory and used with JsonSerializer.Deserialize throughout the integration layer.

.NET developer building a GitHub repository analyser

A developer builds a .NET console tool that queries the GitHub REST API to generate contributor statistics. The GitHub API returns detailed JSON objects for repositories, commits, and contributors. The developer pastes a real API response into this generator and produces the C# class hierarchy — Repository, Owner, License, Topics — in seconds. The generated classes are used with HttpClient.GetFromJsonAsync<Repository>() in .NET 5+, which deserialises directly from the HTTP response stream.

Azure Function processing IoT device telemetry

A platform engineer implements an Azure Function triggered by IoT Hub messages from manufacturing floor sensors. Each message is a JSON payload containing device ID, timestamp, temperature, pressure, and alarm status. The engineer generates a SensorReading C# class from a sample message, uses it as the strongly typed input binding, and writes the function body knowing that all property accesses are compile-time checked. The function processes thousands of messages per minute, and the typed approach makes the code easier to maintain and test than string-based JSON parsing.

Blazor developer building a data dashboard

A Blazor WebAssembly developer builds a business intelligence dashboard that displays sales data from an internal REST API. The API returns paginated JSON responses with data arrays and metadata. The developer generates the C# response model classes from a real API response, places them in a shared class library referenced by both the Blazor app and the API project, and uses them to type both the HTTP calls in the Blazor app and the controller return types in the API — ensuring that any change to the response structure is caught immediately by the compiler across both projects.

Common Mistakes and Troubleshooting

Nullable reference types and null handling

C# 8.0 introduced nullable reference types (#nullable enable). With nullable reference types enabled, string is non-nullable by default — assigning or deserialising null to it produces a compiler warning. For JSON fields that can be null, use string?. For value types that can be null (int, bool, double), use int? (equivalent to Nullable<int>). The generator adds ? to types that were null in the sample. If your project does not use nullable reference types, the ? on reference types has no effect and can be left as-is or removed.

PascalCase property names not matching camelCase JSON keys

C# property naming convention is PascalCase (UserName), while JSON APIs typically use camelCase (userName) or snake_case (user_name). System.Text.Json by default uses case-sensitive matching and expects property names to match exactly. Add [JsonPropertyName("userName")] to each property, or configure the serialiser globally with options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase. The generator adds [JsonPropertyName] attributes for any property whose JSON key does not match the C# property name.

Deserialisation returning null instead of the object

If JsonSerializer.Deserialize<MyClass>(jsonString) returns null instead of an object, the JSON was the literal null value or empty. Check that the JSON string is non-null and non-empty before deserialising. The return type of Deserialize<T> is T? (nullable) — always check for null: var result = JsonSerializer.Deserialize<User>(json) ?? throw new InvalidOperationException("JSON was null");.

System.Text.Json not supporting all Newtonsoft.Json features

System.Text.Json is faster than Newtonsoft.Json but has a smaller feature set. Features available in Newtonsoft.Json but absent or limited in System.Text.Json include: reference loops handling, camelCase dictionary keys, some DateTimeOffset formats, and [JsonConstructor] behaviour differences. If you are migrating from Newtonsoft to System.Text.Json and encounter issues, consult the Microsoft migration guide.

Root-level JSON arrays deserialising incorrectly

To deserialise a JSON array into a C# collection, specify the collection type: var users = JsonSerializer.Deserialize<List<User>>(jsonString); or var users = JsonSerializer.Deserialize<User[]>(jsonString);. Do not try to deserialise an array-rooted JSON into a non-collection class — Deserialize<User> expects a JSON object, not a JSON array, and will throw a JsonException if given an array.

Last reviewed: June 7, 2026

Frequently Asked Questions

What C# types are generated for each JSON value type?
JSON strings become C# string. JSON integers become int or long (long for values that may exceed int's range of ~2.1 billion). JSON floats become double. JSON booleans become bool. JSON null values produce nullable types: string? for reference types (C# 8+) or int? (Nullable<int>) for value types. JSON objects become named classes. JSON arrays become List<T> or T[] — for example, a JSON array of strings becomes List<string> and an array of objects becomes List<User>.
What is the difference between System.Text.Json and Newtonsoft.Json?
System.Text.Json is the built-in .NET JSON library since .NET Core 3.0. It is faster, allocates less memory, and is the default in ASP.NET Core. Newtonsoft.Json (Json.NET) is the older, more feature-rich library that was the standard before .NET Core 3.0. Newtonsoft supports more edge cases, has more configuration options, and has broader community support for older patterns. For new .NET 5+ projects, use System.Text.Json. If you maintain a legacy project or need features not in System.Text.Json (like circular reference handling), Newtonsoft is still appropriate.
How do I deserialise JSON into the generated C# class?
With System.Text.Json: var user = JsonSerializer.Deserialize<User>(jsonString). For root-level arrays: var users = JsonSerializer.Deserialize<List<User>>(jsonString). In ASP.NET Core, HTTP controller actions automatically deserialise [FromBody] parameters — just declare the type: public IActionResult Create([FromBody] User user). With HttpClient: var user = await httpClient.GetFromJsonAsync<User>("/api/user/1") — available in .NET 5+ without additional code.
What is the [JsonPropertyName] attribute and when do I need it?
The [JsonPropertyName("keyName")] attribute from System.Text.Json maps a C# property to a specific JSON key. Use it when the JSON key name does not match the C# property name: [JsonPropertyName("created_at")] public string CreatedAt { get; set; }. Without it, System.Text.Json uses the property name verbatim (case-sensitive by default). For Newtonsoft.Json, use [JsonProperty("created_at")] instead. The generator adds these attributes automatically for any property where the JSON key and C# property name differ.
Can I generate C# records instead of classes?
C# records (introduced in C# 9 / .NET 5) are immutable reference types ideal for data transfer objects. A record: public record User(string Name, int Age); automatically generates a constructor, value equality, and a with expression for non-destructive mutation. System.Text.Json supports records from .NET 5+. To use a record as a deserialisation target, it needs either a parameterless constructor (with optional init-only properties) or [JsonConstructor] on the primary constructor. Manually converting the generated class to a record is straightforward for simple flat structures.
How do I handle nullable reference types in the generated code?
With C# nullable reference types enabled (#nullable enable or <Nullable>enable</Nullable> in the project file), string? indicates a nullable reference type that can be null, while string is non-nullable. The generator adds ? to reference type properties that had null values in the JSON sample. If your project does not enable nullable reference types, the ? suffix on reference types has no semantic effect and can be left as-is. For value types like int?, the ? always means Nullable<int> regardless of the nullable reference types setting.
How are nested JSON objects handled in C# classes?
Each nested JSON object becomes a separate C# class. The class name is derived from the property name in PascalCase — an address property produces an Address class, and shippingDetails produces a ShippingDetails class. The parent class has a property of the nested class type: public Address? Address { get; set; }. All generated classes must be in the same namespace or referenced via using statements for the type references to resolve correctly.
How do I configure System.Text.Json for camelCase property names globally?
In ASP.NET Core, camelCase is the default JSON output policy since .NET Core 3.0. To configure explicitly: services.AddControllers().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase). For standalone JsonSerializer usage: var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true }; var user = JsonSerializer.Deserialize<User>(json, options). With this configuration, C# PascalCase properties automatically map to camelCase JSON without [JsonPropertyName] attributes.
How do I use the generated classes with HttpClient?
In .NET 5+, use the GetFromJsonAsync and PostAsJsonAsync extension methods from System.Net.Http.Json: var user = await client.GetFromJsonAsync<User>("/api/user/1"); and await client.PostAsJsonAsync("/api/users", newUser). These methods handle serialisation, deserialisation, and error checking in one call. For .NET Core 3.x without these extensions, use: var response = await client.GetAsync(url); var user = await JsonSerializer.DeserializeAsync<User>(await response.Content.ReadAsStreamAsync()).
What happens when a JSON field has a value type that changes?
If a JSON field is sometimes an integer and sometimes a string (which occasionally happens in poorly designed APIs), the generator cannot produce a precise type — it may produce object or a union-like approach. In C#, handle this with a custom JsonConverter: implement JsonConverter<MyType>, register it with [JsonConverter(typeof(MyConverter))] on the property, and handle both value types in the Read() method. This is preferable to using dynamic or JsonElement, which lose type safety.

Rate This Tool

Was this tool helpful?

Be the first to rate this tool

About the Author

S. Siddiqui

S. Siddiqui

Founder & Editor-in-Chief

LinkedIn Profile

S. Siddiqui is the founder and editor-in-chief of YourToolsBase, overseeing all content, tool accuracy, and editorial standards.

View full profile

Authoritative Sources

Formulas and data in this tool are based on guidelines from the above sources.