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

如何将含任意数量值与属性的JSON反序列化为C#类

问题分析与解决方案

现有C#类的问题

你定义的Dictionary<object, List<customchild>>无法适配JSON中customchild_xxx的三种值类型(对象、数组、null):

  • 键的实际类型是字符串(如customchild_1),而非object;
  • 值的类型不统一,List<customchild>只能解析对象数组,无法处理单个对象、null或字符串数组的情况。

修正后的类定义

使用Newtonsoft.Json(Json.NET)的JToken类型可以兼容任意JSON值,类结构如下:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class RootObject
{
    public long timestamp { get; set; }
    public Parent parent { get; set; }
}

public class Parent
{
    public string id { get; set; }
    public string key { get; set; }
    public Dictionary<string, JToken> childs { get; set; }
}

public class CustomChild
{
    public string value { get; set; }
    public string id { get; set; }
}

如果使用System.Text.Json,可替换为Dictionary<string, JsonElement>,处理逻辑一致。


1. 统计customchild属性数量

直接读取字典的元素数量即可,每个键对应一个customchild_xxx属性:

// 假设已反序列化得到RootObject实例 root
int childCount = root.parent.childs.Count;

2. 访问第N个customchild的内容

由于字典默认无序,需先按customchild_后的数字排序,再根据索引访问:

int targetN = 4; // 要访问第4个customchild(从1开始计数)
var childsDict = root.parent.childs;

// 按customchild_后缀的数字排序键
var sortedChildKeys = childsDict.Keys
    .OrderBy(key => int.Parse(key.Split('_')[1]))
    .ToList();

if (targetN > 0 && targetN <= sortedChildKeys.Count)
{
    string targetKey = sortedChildKeys[targetN - 1];
    JToken childValue = childsDict[targetKey];

    // 根据值类型解析内容
    switch (childValue.Type)
    {
        case JTokenType.Object:
            var childObj = childValue.ToObject<CustomChild>();
            // 使用childObj.value和childObj.id
            break;
        case JTokenType.Array:
            var childArray = childValue.ToObject<List<string>>();
            // 使用字符串数组
            break;
        case JTokenType.Null:
            // 处理null值
            break;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:55:25