You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中为指定JSON数据创建对应属性?

在C#中为给定JSON创建实体类的方案

嘿,这事儿不难,我们可以直接匹配JSON的结构来构建对应的C#实体类,同时遵循C#的命名规范(PascalCase),通过序列化特性来映射JSON里的snake_case字段。

首先先回顾下你提供的原始JSON结构:

{
"charts":[ "CaseStatusChart", "InvoiceStatusChart", "QuoteStatusChart" ],
"recent_activities":[ "Accounts", "Cases", "Calls" ],
"counters":[ "Cases", "Calls", "Accounts", "Documents" ]
}

下面分两种常用的序列化库给出实现:

1. 使用System.Text.Json(.NET Core/.NET 5+ 默认)

这是微软官方内置的序列化库,不需要额外安装包,用JsonPropertyName特性来映射字段:

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

public class DashboardConfig
{
    // 映射JSON中的"charts"字段
    [JsonPropertyName("charts")]
    public List<string> Charts { get; set; } = new List<string>();

    // 映射JSON中的"recent_activities"字段
    [JsonPropertyName("recent_activities")]
    public List<string> RecentActivities { get; set; } = new List<string>();

    // 映射JSON中的"counters"字段
    [JsonPropertyName("counters")]
    public List<string> Counters { get; set; } = new List<string>();
}

2. 使用Newtonsoft.Json(Json.NET,经典第三方库)

如果你的项目还在使用传统的Json.NET,就用JsonProperty特性:

using System.Collections.Generic;
using Newtonsoft.Json;

public class DashboardConfig
{
    [JsonProperty("charts")]
    public List<string> Charts { get; set; } = new List<string>();

    [JsonProperty("recent_activities")]
    public List<string> RecentActivities { get; set; } = new List<string>();

    [JsonProperty("counters")]
    public List<string> Counters { get; set; } = new List<string>();
}

小提示

  • 我给每个属性都初始化了空列表,这样在反序列化的时候如果JSON里某个数组缺失,也不会出现NullReferenceException,更安全。
  • 如果你的项目全局配置了序列化规则(比如自动将snake_case转换为PascalCase),那可以省略这些特性标签,但显式加上能让代码更清晰,避免后续规则变动导致的问题。

内容的提问来源于stack exchange,提问作者Hardik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:00:39