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

如何读取ValueKind=Array类型的dynamic变量?

读取ValueKind=Array类型dynamic变量的方法

当你用System.Text.Json反序列化得到dynamic类型的数组时,这个变量实际是JsonElement实例,直接遍历会报错,以下是几种可行的读取方式:

方法1:转换为字符串数组

直接将JsonElement转换为string[],简单直接:

if (dictionary.TryGetValue("memberList", out dynamic? value))
{
    // 先将dynamic转为JsonElement,再转换为字符串数组
    var memberArray = ((JsonElement)value).Deserialize<string[]>();
    if (memberArray != null)
    {
        foreach (var item in memberArray)
        {
            Console.WriteLine(item); // 输出"a"、"b"
        }
    }
}

方法2:遍历JsonElement的枚举器

如果不想直接转数组,也可以通过JsonElement.EnumerateArray()遍历每个元素:

if (dictionary.TryGetValue("memberList", out dynamic? value))
{
    var jsonElement = (JsonElement)value;
    foreach (var element in jsonElement.EnumerateArray())
    {
        string item = element.GetString(); // 获取字符串值
        Console.WriteLine(item);
    }
}

方法3:强类型反序列化(更推荐)

如果你提前知道结构,最好直接反序列化为强类型字典,避免dynamic的不确定性:

// 定义强类型字典,值为字符串数组
var dictionary = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string[]>>(response);
if (dictionary.TryGetValue("memberList", out var memberArray))
{
    foreach (var item in memberArray)
    {
        Console.WriteLine(item);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:42:04