Tool Kumar 工具

JSON 转 C# 实体类

为 System.Text.Json 生成 C# 模型。默认输出会为每个属性加上 JsonPropertyName 特性,并对每条示例记录中都存在的字段使用 required。

如何使用这个工具

  1. 粘贴一份有代表性的响应,其中应包含字段存在差异的记录。
  2. 检查生成的输出,必要时修改根名称。
  3. 复制或下载代码,然后对照你的 API 契约检查类型。

示例演示

以下输出来自内置转换器。两个数组元素的 price 值用于推断浮点型字段;note 值分别为 null 和字符串,因此推断为可空字段。

输入

{
  "user-id": 42,
  "profile": {
    "city": "London",
    "created_at": "2026-10-14T09:00:00Z"
  },
  "items": [
    {
      "price": 12,
      "note": null
    },
    {
      "price": 12.5,
      "note": "gift"
    }
  ]
}

输出

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

public class Root
{
    [JsonPropertyName("user-id")]
    public required long UserId { get; set; }

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

    [JsonPropertyName("items")]
    public required List<Item> Items { get; set; }
}

public class Profile
{
    [JsonPropertyName("city")]
    public required string City { get; set; }

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

public class Item
{
    [JsonPropertyName("price")]
    public required double Price { get; set; }

    [JsonPropertyName("note")]
    public required string? Note { get; set; }
}

用 System.Text.Json 反序列化

把这些类复制到你的 .NET 项目中,并启用可为 null 注释。JsonPropertyName 特性会把 PascalCase 属性映射到输入中的确切键名。

请使用 System.Text.Json 支持 required 成员的 .NET 版本,例如 .NET 7 或更高版本,并根据你的应用配置序列化器选项。

using System.Text.Json;

Root? model = JsonSerializer.Deserialize<Root>(responseBody);

选项与特殊情况

  • 默认使用 System.Text.Json。在“更多选项”中选择 Newtonsoft,即可生成 Newtonsoft.Json 的 JsonProperty 特性,未知值使用 JToken。
  • 生成的 required 成员需要 C# 11 或更高版本。使用可为 null 的引用类型语法时,假定项目已启用可为 null 注释。
  • 整数使用 long,超出有符号 64 位范围的整数使用 decimal,小数使用 double。decimal 的范围同样有限;更大的值请自行选择表示方式。
  • 当每条记录都包含某个键时,可为 null 的字段仍然可以是 required。“必须存在”和“允许为 null”是两条独立的规则。日期保持为 string。

默认保护隐私

你的文档只保留在这个浏览器中。Tool Kumar 在你的设备上解析、转换并生成下载文件,无需账号,也没有上传步骤。

JSON 转 C# 实体类:常见问题

使用 System.Text.Json 还是 Newtonsoft.Json?
默认使用 System.Text.Json,生成 JsonPropertyName 特性。在转换器的“更多选项”菜单中选择 Newtonsoft,即可改为生成 Newtonsoft.Json 的 JsonProperty 特性。
输出需要哪个 C# 版本?
required 成员需要 C# 11 或更高版本。启用可为 null 的引用类型后,string? 等引用类型注释才能按预期工作。
为什么 required 属性还可以为 null?
这个键出现在每条示例记录中,但它的值可能是 null。例如 required string? Note 就把“是否存在”和值的类型分开表达。
会生成列表和嵌套类吗?
会。对象数组会变成 List<Item>,每种嵌套结构都会生成一个类。

相关工具

JSON 转 Java 实体类、JSON 转 TypeScript和JSON Schema 生成器。