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

ASP.Net Core 3.1 反序列化含未知动态键名的JSON的问题咨询

.NET 3.1 动态键JSON反序列化解决方案

你可以通过「字典映射」或者「手动遍历JSON节点」两种方式实现需求,以下是两种主流JSON处理库的实现代码:

前置准备:定义内层实体类

首先声明嵌套结构对应的实体类:

public class UserInfo
{
    public int id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
}

方案1:字典反序列化(最简便)

因为顶层是动态字符串键、值结构固定,直接把整个JSON反序列化为Dictionary<string, UserInfo>即可,自动适配所有动态顶层键。

使用 Newtonsoft.Json(Json.NET)实现

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

// 反序列化代码
string json = "你的JSON字符串";
Dictionary<string, UserInfo> result = JsonConvert.DeserializeObject<Dictionary<string, UserInfo>>(json);

// 提取属性
foreach (var item in result.Values)
{
    string firstName = item.first_name;
    string lastName = item.last_name;
    // 后续业务逻辑
}

使用 System.Text.Json(.NET Core 3.1 原生库)实现

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

// 反序列化代码
string json = "你的JSON字符串";
Dictionary<string, UserInfo> result = JsonSerializer.Deserialize<Dictionary<string, UserInfo>>(json);

// 提取属性
foreach (var item in result.Values)
{
    string firstName = item.first_name;
    string lastName = item.last_name;
    // 后续业务逻辑
}

方案2:手动解析节点(适合仅提取少量字段场景)

如果不需要全量反序列化整个实体,可以直接解析JSON节点获取目标属性:

Newtonsoft.Json 版本

using Newtonsoft.Json.Linq;

string json = "你的JSON字符串";
JObject jObj = JObject.Parse(json);
foreach (var child in jObj.Children().Values())
{
    string firstName = child["first_name"].ToString();
    string lastName = child["last_name"].ToString();
}

System.Text.Json 版本

using System.Text.Json;

string json = "你的JSON字符串";
JsonDocument doc = JsonDocument.Parse(json);
foreach (var property in doc.RootElement.EnumerateObject())
{
    string firstName = property.Value.GetProperty("first_name").GetString();
    string lastName = property.Value.GetProperty("last_name").GetString();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:36:01