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

C#中使用System.Text.Json反序列化含可变子根名的JSON类结构定义

解决方案

针对你描述的JSON结构(textClasses节点下包含动态命名的子节点,如callout、title等),最适配的方式是用**字典(Dictionary)**承载这些可变子节点,结合基础类定义子节点的通用属性。

示例JSON结构

假设你的JSON文件内容大致如下:

{
  "textClasses": {
    "callout": {
      "fontSize": 14,
      "color": "#333"
    },
    "title": {
      "fontSize": 24,
      "bold": true
    },
    "header": {
      "fontSize": 18,
      "underline": true
    },
    "label": {
      "fontSize": 12,
      "italic": true
    }
  }
}

定义C#类结构

  1. 基础属性类:描述textClasses下每个子节点的属性,若存在不确定的额外属性,可通过JsonExtensionData捕获
public class TextClass
{
    [JsonPropertyName("fontSize")]
    public int FontSize { get; set; }

    [JsonPropertyName("color")]
    public string? Color { get; set; }

    [JsonPropertyName("bold")]
    public bool? Bold { get; set; }

    [JsonPropertyName("underline")]
    public bool? Underline { get; set; }

    [JsonPropertyName("italic")]
    public bool? Italic { get; set; }

    // 捕获未定义的额外属性,避免反序列化失败
    [JsonExtensionData]
    public Dictionary<string, JsonElement>? ExtraProperties { get; set; }
}
  1. 根对象类:包含textClasses字典属性,键对应动态子节点名,值对应上述TextClass实例
public class RootObject
{
    [JsonPropertyName("textClasses")]
    public Dictionary<string, TextClass> TextClasses { get; set; } = new Dictionary<string, TextClass>();
}

反序列化代码示例

// 读取JSON文件内容
string jsonContent = File.ReadAllText("your-json-file.json");

// 反序列化为RootObject实例
RootObject result = JsonSerializer.Deserialize<RootObject>(jsonContent)!;

// 访问指定子节点(如callout)
if (result.TextClasses.TryGetValue("callout", out var calloutClass))
{
    Console.WriteLine($"Callout字体大小:{calloutClass.FontSize},颜色:{calloutClass.Color}");
}

// 遍历所有textClasses子节点
foreach (var (className, classProps) in result.TextClasses)
{
    Console.WriteLine($"文本类:{className},字体大小:{classProps.FontSize}");
}

补充说明

  • 若textClasses下的子节点结构差异极大,也可直接用Dictionary<string, JsonElement>存储,之后针对每个节点单独解析,但使用TextClass能获得更好的类型安全性。
  • JsonExtensionData属性会自动捕获所有未在类中定义的属性,避免因JSON结构新增字段导致反序列化失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:42:15