JSON ke C#
Belum ada konten
Alat online JSON ke C# mengonversi respons API atau JSON konfigurasi menjadi kelas C# standar untuk ASP.NET Core, Unity, Blazor, .NET MAUI. Mendukung [JsonProperty], List, Nullable<T>, kelas bersarang, pembuatan lokal.
Belum ada konten
Alat online JSON ke C# mengonversi respons API atau JSON konfigurasi menjadi kelas C# standar untuk ASP.NET Core, Unity, Blazor, .NET MAUI. Mendukung [JsonProperty], List, Nullable<T>, kelas bersarang, pembuatan lokal.
JSON to C# is the process of converting JSON-formatted data (objects or arrays) into C# class definitions (POCO, Plain Old CLR Object). C# is the primary language of the .NET ecosystem, widely used in ASP.NET Core backends, Unity games, .NET MAUI cross-platform apps, Blazor WebAssembly, desktop apps (WPF / WinForms), Azure cloud services, and more. Development often requires converting JSON samples from API docs or actual responses into C# types; writing classes manually is not only repetitive but also error-prone for field types and annotations. This tool aims to automate that process.
This tool runs locally in the browser based on quicktype-core, using the C# renderer to generate standard POCO class code. Default output includes using System.Collections.Generic; and [JsonProperty("original key")] annotations (Newtonsoft.Json compatibility mode), directly openable and compilable in Visual Studio. This means you receive not just a type draft but C# classes that can be placed into .NET projects and used with NuGet packages.
Type inference is at the core of JSON to C#. The tool maps JSON primitive types to .NET standard types: strings → string, integers → long, floats → double, booleans → bool, arrays → List<T>, nested objects → independent classes, null values → Nullable<T> (e.g., long? / bool? / string?). For nested objects, the tool automatically creates new classes for each level, named by capitalizing field names. For example, the address field generates an Address class, and objects in items arrays generate an Item class.
Integration with modern C# syntax: this tool defaults to generating serializable POCOs (public { get; set; } properties). For projects pursuing immutability, developers can change class to C# 9+ record types and change { get; set; } to init-only properties (public string Name { get; init; }), which with JsonSerializer.Deserialize<T>(jsonString) guarantees at compile time that data cannot be modified. This aligns with ASP.NET Core 7+ Minimal APIs and Entity Framework Core 8+ immutable entity design trends.
Unlike some online tools that require uploading JSON to servers, all computations in this tool happen in the browser. quicktype-core loads and executes via Web Worker; JSON parsing, type inference, C# code generation, and file downloads all occur locally with no data sent to any server. This is especially important for JSON containing API keys, user-private fields, or unreleased business structures; data is cleared from memory when the page is closed.
Note that auto-generated code is a starting point, not an endpoint. The tool infers types from JSON samples and cannot determine precise business types (e.g., URL, Email, ID and other semantic types are all inferred as string). For snake_case JSON fields, C# fields maintain PascalCase naming (user_name → UserName), but [JsonProperty("user_name")] annotations retain original keys for automatic mapping during deserialization. Treat generated results as a first draft, then fine-tune field names, types, and attributes according to project conventions.
Most common usage in ASP.NET Core projects: deserialize API responses using Newtonsoft.Json with POCOs generated by this tool.
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class ApiClient
{
private static readonly HttpClient _http = new HttpClient();
// POCO generated by this tool:
public class User
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("is_active")]
public bool? IsActive { get; set; }
}
public static async Task<User> GetUserAsync(int userId)
{
// 1) Call API to get JSON string
var json = await _http.GetStringAsync($"https://api.example.com/users/{userId}");
// 2) Deserialize to POCO generated by this tool
// Internally maps snake_case JSON via [JsonProperty("id")] etc. annotations
var user = JsonConvert.DeserializeObject<User>(json);
Console.WriteLine($"User: {user.Name} ({user.Email})");
return user;
}
}Place the User POCO generated by this tool in an ASP.NET Core Controller to automatically receive frontend JSON requests with [FromBody].
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
// POCO generated by this tool (defaults to Newtonsoft [JsonProperty]):
public class CreateOrderRequest
{
[Newtonsoft.Json.JsonProperty("user_id")]
public long UserId { get; set; }
[Newtonsoft.Json.JsonProperty("items")]
public List<OrderItem> Items { get; set; }
}
public class OrderItem
{
[Newtonsoft.Json.JsonProperty("product_id")]
public long ProductId { get; set; }
[Newtonsoft.Json.JsonProperty("quantity")]
public long Quantity { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpPost]
public IActionResult Create([FromBody] CreateOrderRequest request)
{
if (request == null || request.Items == null || !request.Items.Any())
{
return BadRequest("Items cannot be empty");
}
// Business logic: save order
// var order = OrderService.Create(request);
return Ok(new { order_id = 12345, status = "created" });
}
}
/*
* Corresponding .csproj dependencies:
* <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.0" />
* <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
*/.NET 5+ / .NET 7+ recommended usage: using System.Text.Json built-in extension methods + record types with [JsonPropertyName] annotations.
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
// This tool defaults to generating POCO class; manually change to record type below (immutable data carrier):
public record User
{
[JsonPropertyName("id")]
public long Id { get; init; }
[JsonPropertyName("name")]
public string Name { get; init; }
[JsonPropertyName("email")]
public string Email { get; init; }
[JsonPropertyName("is_active")]
public bool? IsActive { get; init; }
}
public class ApiClient
{
private static readonly HttpClient _http = new HttpClient();
public static async Task<User> GetUserAsync(int userId)
{
// System.Text.Json: GetFromJsonAsync accomplishes HTTP + deserialization in one line
var user = await _http.GetFromJsonAsync<User>(
$"https://api.example.com/users/{userId}");
System.Console.WriteLine($"User: {user.Name} ({user.Email})");
return user;
}
}
/*
* Corresponding .csproj dependencies (System.Text.Json is built-in, no extra installation needed):
* <TargetFramework>net7.0</TargetFramework>
*
* If your project is .NET 7+ and you want to use [JsonProperty] compatible with Newtonsoft syntax,
* add in Program.cs:
* builder.Services.AddControllers()
* .AddNewtonsoftJson(options =>
* {
* options.SerializerSettings.ContractResolver =
* new Newtonsoft.Json.Serialization.DefaultContractResolver();
* });
*/Add <Nullable>enable</Nullable> in .csproj; nullable types like string? / List<User>? generated by this tool automatically get compile-time null checks, avoiding NullReferenceException runtime crashes.
This tool automatically converts JSON fields to PascalCase (e.g., user_name → UserName), while retaining the original key in [JsonProperty] annotations. This makes code conform to .NET official naming conventions while deserialization still works with original JSON keys.
When nesting exceeds 4 levels, recommend splitting the root object into multiple independent POCOs responsible for different business domains (e.g., UserDto / OrderDto / PaymentDto), avoiding one giant class containing all fields, improving maintainability.
Don't use POCOs generated by this tool as both EF Core Entities and API DTOs. Recommend: ① API layer uses DTOs (generated from JSON); ② EF Core layer uses Entities (manually add [Key] / [Required] etc. data annotations); ③ Do DTO ↔ Entity mapping via AutoMapper / Mapster. Avoid directly exposing database structure to frontend.
If your project uses System.Text.Json, recommend using IDE global replace to change generated [JsonProperty("xxx")] to [JsonPropertyName("xxx")]. Or keep original [JsonProperty] + install Microsoft.AspNetCore.Mvc.NewtonsoftJson package and call AddNewtonsoftJson() to support Newtonsoft syntax.
All calculations in this tool are done locally in the browser, but recommend adding another layer of protection in enterprise settings: ① Don't copy JSON containing production DB connection strings / API master keys to any online tool; ② For internal POCO generation, recommend NSwag or Visual Studio Paste JSON as Classes for completely offline generation; ③ Only use online tools with desensitized sample JSON.
JSON larger than 1MB renders slowly in browsers. Recommendations: ① Split into multiple independent POCO classes (e.g., User.cs / Address.cs / Order.cs) categorized by business module; ② For extra-large JSON Schema (100+ fields) use NSwag or Visual Studio built-in to directly generate; ③ Only use this tool for small-to-medium API responses (< 100 fields).
For DTOs / response models that don't need modification, recommend changing generated class to C# 9+ record and { get; set; } to { get; init; }. This: ① Guarantees data cannot be modified at compile time; ② Automatically gets value equality comparison (Equals / GetHashCode); ③ Simplifies object copying with with expressions.
Paste JSON content into the left input box; the tool automatically calls quicktype-core within 400ms to generate C# classes, with complete code displayed on the right. You can also click the 'Upload' button to select .json / .txt files, or click 'Example' to load built-in data. After generation, click the 'Copy' button to copy an individual class to the clipboard, or download as a .cs file.
Yes. The tool defaults to Newtonsoft.Json compatibility mode, automatically adding [JsonProperty("original key")] attributes for each field. This ensures that even if field names are converted to PascalCase, deserialization still correctly maps to the original JSON keys. If you use System.Text.Json, you can change [JsonProperty] to [JsonPropertyName] after generation (same semantics), or directly use System.Text.Json's default naming policy ([JsonPropertyName] in System.Text.Json can also be handled via custom JsonNamingPolicy).
By default it generates serializable POCO classes (with { get; set; } properties). If your project uses C# 9+ record types (immutable data carriers, suitable for DTOs / immutable models), you can manually change class to record after generation, and change { get; set; } to init-only properties (public string Name { get; init; }). Record types are widely used in ASP.NET Core 7+ Minimal APIs and Entity Framework Core.
All valid JSON structures are supported: basic types (null, boolean, number, string), arrays (1D or multi-dimensional), nested objects (any depth). Root input can be JSON object or JSON array; JSON objects generate public class Root, JSON arrays generate public class Root : List<Item>. JavaScript-specific values (functions, Symbols, undefined, Date objects, etc.) are not supported.
String → string, integer → long, float → double, boolean → bool, array → List<T>, nested object → independent class, null value fields → Nullable<T> (e.g., long? / bool? / string?). See the 'JSON Type to C# Type Mapping Quick Reference' table at the bottom of the page for detailed mapping rules.
Yes. The tool detects fields that are explicitly null or missing in JSON, automatically generating them as Nullable<T> form (e.g., long? Id { get; set; }). This is consistent with the Nullable Reference Types (NRT) feature introduced in C# 8, enabling the compiler to help you discover null reference risks during static analysis. Note: if you have NRT enabled, reference types default to non-nullable; you need to explicitly write string? to indicate nullability.
Yes. JSON arrays are uniformly converted to C# List<T>, with element types auto-inferred from the first array element. String arrays → List<string>, integer arrays → List<long>, object arrays → List<Item>. Empty arrays [] default to List<object> because element type cannot be inferred; it's recommended to manually change to a concrete type after generation (e.g., List<MyClass>). If you prefer T[] array syntax, use IDE Find & Replace to batch replace after generation.
The tool generates an independent C# class for each nested object. Naming convention capitalizes the field name (e.g., address → Address). If the root object contains an items array whose elements are objects, it generates a public class Item class, then referenced by public List<Item> Items { get; set; }. Objects with the same structure reuse the same type to avoid duplicate definitions.
Yes. quicktype-core defaults to using the JSON source name (e.g., Root) as the root class name. You can manually modify class names, namespace, and all references after generation. Downloaded .cs filenames can also be renamed as needed when saving (e.g., User.cs, Order.cs).
Yes, directly usable. Generated files are standard C# syntax including using System.Collections.Generic; references. Place .cs files in the root or subdirectory of your .NET project; no additional dependencies are needed in .csproj (System.Text.Json is built into .NET; Newtonsoft.Json requires NuGet installation of Microsoft.AspNetCore.Mvc.NewtonsoftJson or Newtonsoft.Json package). Then you can deserialize with JsonConvert.DeserializeObject<T>(jsonString) or JsonSerializer.Deserialize<T>(jsonString).
Fully local browser operation. All JSON parsing, C# code generation, and file downloads are done in-browser via JavaScript + WebAssembly. Neither your input JSON data nor generated C# code are uploaded to any server, nor are they logged or cached in the cloud. Sensitive JSON containing API keys, tokens, or undisclosed business fields can be used safely; data is cleared when the page is closed.
No. The tool is completely free, no registration, login, or authorization required. Just open the page and use it. All features are available locally in the browser.
The tool automatically checks JSON validity. On error, a red error message appears on the right with a 'Fix JSON' button. Clicking it auto-repairs common errors: trailing commas, single quotes replaced with double quotes, missing quotes on keys completed, comments removed, etc. After successful repair, C# code generation continues.
Both are the most mainstream JSON libraries in the .NET ecosystem. Newtonsoft.Json (also known as Json.NET) is the oldest, most ecosystem-rich library compatible with almost all .NET projects; System.Text.Json is the high-performance library built into .NET Core 3.0+, faster startup, less memory, AOT-friendly. ASP.NET Core 3.0+ defaults to System.Text.Json; legacy .NET Framework projects and many third-party libraries rely on Newtonsoft.Json by default. This tool defaults to generating [JsonProperty] compatible with both (System.Text.Json in .NET 7+ also supports Newtonsoft compatibility via Microsoft.AspNetCore.Mvc.NewtonsoftJson).
All three convert JSON to target language type definitions, but output forms differ: JSON to C# generates POCO classes with [JsonProperty] annotations that can be directly deserialized with Newtonsoft.Json or System.Text.Json; JSON to Java generates POJOs with Lombok/Gson/Jackson annotations; JSON to Rust generates structs with Serde derive. Each focuses on different ecosystems; choose based on your tech stack.
System.Text.Json doesn't support automatic string-to-DateTime conversion by default and throws JsonException. Two solutions: ① Add [JsonConverter(typeof(DateTimeConverter))] custom converter on the field; ② Configure global JsonSerializerOptions in Program.cs: options.PropertyNameCaseInsensitive = true; and handle DateTime via custom JsonConverter. Newtonsoft.Json supports DateTime deserialization by default, but special formats (like Unix timestamps) also require custom converters.
The tool doesn't generate namespace by default to maintain maximum compatibility for code snippets, making it easy for users to copy into any project. If you need namespace, manually add namespace YourApp.Models; at the top of generated code and place classes in corresponding .cs files. In .NET projects, organizing namespaces by functional module (Models / Dtos / ViewModels / Entities) is recommended.
Visual Studio 2019+ has built-in 'Paste Special → Paste JSON as Classes' feature (Edit menu → Paste Special), which can directly convert JSON to C# classes. Code generated by this tool is compatible with that feature: copy C# code generated by the tool to clipboard, then paste into any .cs file for use. If you prefer the VS built-in feature, you can directly use Edit → Paste Special → Paste JSON as Classes without opening this tool.
The left input box is empty or contains only whitespace. Ensure valid JSON content is pasted, or click the upload button to select a .json / .txt file; you can also click the example button to load built-in samples.
Common causes: trailing commas (e.g., {"a":1,}), using single quotes instead of double quotes, unquoted keys, containing JavaScript comments. Click the 'Fix JSON' button to auto-repair some errors; if it still fails, validate with a JSON formatting tool first.
The tool infers types from JSON samples; for example all integers are long and all strings are string. If you need more precise types like int / decimal / Guid / DateTime, manually modify field types after generation. Note System.Text.Json doesn't support DateTime by default; [JsonConverter] customization is needed.
The tool defaults to generating in C# 8+ Nullable Reference Types form (e.g., string? / List<User>?). If your project is an older .NET Framework version / NRT not enabled, all reference types default to nullable; the ? in string? can simply be deleted (or enable <Nullable>enable</Nullable> in .csproj).
Add the following PackageReference in .csproj: <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> </ItemGroup> Then run dotnet restore; NuGet downloads automatically. If using System.Text.Json no installation is needed (.NET built-in).
The tool automatically converts JSON field names to PascalCase (e.g., user_name → UserName), while retaining the original key in [JsonProperty] annotations. Newtonsoft.Json deserializes according to [JsonProperty] mappings without manual handling. If using System.Text.Json default naming policy, you need to change [JsonProperty] to [JsonPropertyName], or configure CamelCase naming policy in Program.cs.
Possible causes: ① Newtonsoft.Json / System.Text.Json dependency not added in .csproj; ② Classes placed in non-standard directories (should be placed in .NET project root or subdirectory with corresponding namespace); ③ Class names conflict with other types in the project. Solutions: add dependencies, adjust directories and namespaces, rename conflicting classes.
ASP.NET Core 3.0+ defaults to System.Text.Json, but [JsonProperty] generated by the tool is Newtonsoft.Json syntax. Two solutions: ① Add Microsoft.AspNetCore.Mvc.NewtonsoftJson package in .csproj and call AddNewtonsoftJson() in Program.cs; ② Change all generated [JsonProperty("xxx")] to [JsonPropertyName("xxx")] (System.Text.Json syntax).
Usually happens when array is empty [] and defaults to List<object>. Add at least one sample element in source JSON (e.g., [1,2,3]); tool infers type from first element; or manually change List<object> to List<long> / List<int> after generation.
Recommend splitting JSON into multiple independent modules for separate conversion, or only extract the portion that needs modeling. Browsers consume significant memory rendering many nested classes; JSON over 5MB recommends NSwag / Visual Studio built-in 'Paste JSON as Classes' for processing.
The tool automatically infers corresponding C# / .NET types based on JSON value types:
| JSON Value Example | Generated C# Type | Nullable Form | Notes |
|---|---|---|---|
null | Inferred from context | T? | null value fields automatically inferred as Nullable<T> (e.g., long? / bool? / string?) |
true / false | bool | bool? | JSON booleans directly map to C# bool |
42 | long | long? | JSON integers default to long (64-bit integer, compatible with large numbers) |
3.14 | double | double? | JSON floats default to double (double-precision floating point) |
"hello" | string | string? | JSON strings map to C# string |
["a","b"] | List<string> | List<string>? | String arrays map to List<string> |
[1,2,3] | List<long> | List<long>? | Integer arrays map to List<long> |
[{...},{...}] | List<Item> | List<Item>? | Object arrays generate corresponding class from first element, then wrapped in List |
[] | List<object> | List<object>? | Empty arrays cannot infer element type, fall back to object; recommend changing to concrete type after generation |
{...} nested object | Independent class | ClassName? | Nested objects generate independent classes, field names capitalized (address → Address) |
Comparison of field mapping attributes between the two mainstream JSON libraries in the .NET ecosystem; this tool defaults to generating Newtonsoft-compatible [JsonProperty]:
| Comparison Item | Newtonsoft.Json | System.Text.Json |
|---|---|---|
Field mapping attribute | [JsonProperty("user_name")] | [JsonPropertyName("user_name")] |
Default naming policy | Keeps PascalCase field names ([JsonProperty] needed for snake_case compatibility) | Keeps original field names (matches by JSON key, CamelCase default) |
Custom naming | [JsonProperty] per-field specification | [JsonPropertyName] + JsonNamingPolicy global configuration |
Null handling | NullValueHandling.Ignore / Include | JsonIgnoreCondition.WhenWritingNull |
Default .NET version | .NET Framework / .NET Core / .NET 5+ | .NET Core 3.0+ / .NET 5+ |
Installation | NuGet: Newtonsoft.Json | Built-in (no installation needed) |
Performance | Medium | High (faster startup, less memory) |
AOT support | Requires source generator | Native support |
Suitable scenarios | Legacy .NET projects, third-party library dependencies, rich ecosystem | ASP.NET Core 3.0+, high-performance scenarios, .NET MAUI / Blazor |
Semua operasi alat JSON ke C# ini diselesaikan sepenuhnya di browser Anda: analisis JSON, pembuatan kode C#, dan unduhan dijalankan di sisi klien via JavaScript + WebAssembly (quicktype-core). Tidak ada konten JSON, file yang diunggah, atau kode yang dihasilkan dikirim melalui jaringan. Unggahan menggunakan FileReader asli langsung di memori. Tidak ada pelacakan Cookie, tidak ada pengumpulan data. Saat menutup halaman semua dihapus.