JSON 转 C# 类
将 JSON 转换为适用于 System.Text.Json 或 Newtonsoft.Json 的 C# 类或记录(record),支持可为 null 的类型、JsonPropertyName 特性,并能识别 DateTimeOffset/Guid。
For strings that look like dates and UUIDs
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class Root
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("username")]
public string Username { get; set; } = string.Empty;
[JsonPropertyName("email")]
public string Email { get; set; } = string.Empty;
[JsonPropertyName("isActive")]
public bool IsActive { get; set; }
[JsonPropertyName("rating")]
public double Rating { get; set; }
[JsonPropertyName("createdAt")]
public DateTimeOffset CreatedAt { get; set; }
[JsonPropertyName("avatarUrl")]
public object? AvatarUrl { get; set; }
[JsonPropertyName("tags")]
public List<string> Tags { get; set; } = new();
[JsonPropertyName("address")]
public Address Address { get; set; } = new();
[JsonPropertyName("orders")]
public List<Order> Orders { get; set; } = new();
}
public class Address
{
[JsonPropertyName("street")]
public string Street { get; set; } = string.Empty;
[JsonPropertyName("city")]
public string City { get; set; } = string.Empty;
[JsonPropertyName("zipCode")]
public string ZipCode { get; set; } = string.Empty;
}
public class Order
{
[JsonPropertyName("orderId")]
public string OrderId { get; set; } = string.Empty;
[JsonPropertyName("total")]
public double Total { get; set; }
[JsonPropertyName("items")]
public int Items { get; set; }
[JsonPropertyName("shipped")]
public bool Shipped { get; set; }
[JsonPropertyName("coupon")]
public string? Coupon { get; set; }
}
Arrays of objects are merged: a key missing from some items becomes optional, null makes a field nullable, and identical shapes share one type. Paste several examples in an array for the most accurate types.
关于此工具
粘贴 JSON,即可得到可直接用于 System.Text.Json 或 Newtonsoft.Json 的 C# 类或记录。属性使用 PascalCase,并带有 [JsonPropertyName] 或 [JsonProperty] 特性,确保每个键都能准确映射回去。可为 null 的引用类型使用得当:可选值和 null 值会变成可为 null 的类型,不为 null 的字符串、列表和对象会获得初始值,因此编译器不会产生 CS8618 警告。整数根据实际值变成 int 或 long,小数变成 double,看起来像时间戳、日期或 UUID 的字符串可以变成 DateTimeOffset、DateOnly 或 Guid。嵌套对象会生成独立的类,列表变成 List<T>,以 ID 为键的对象变成 Dictionary<string, T>。您可以选择文件范围的命名空间,并在同一页面切换到 Go、Rust、Python 或 Kotlin。
如何将 JSON 转换为 C# 类
根据 JSON 示例生成 C# 类型。
- 1
粘贴 JSON
粘贴一个 JSON 对象,或一个示例数组。
- 2
选择选项
选择 System.Text.Json 或 Newtonsoft、类或记录,以及命名空间。
- 3
复制代码
复制类或下载 Types.cs。