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

如何将扁平JSON反序列化为List<KeyValuePair<string, string>>?

将扁平JSON反序列化为List<KeyValuePair<string, string>>的解决方案

发布问题后我立刻意识到自己没使用Dictionary<string, string>的问题,于是马上删除了问题。但不小心又恢复了,抱歉浪费大家时间。我会保留问题,以防其他人也犯同样的糊涂。

问题描述

我有如下扁平JSON:

{
    "name1": "value1",
    "name2": "value2",
    "name3": "value3"
}

由于无法预知属性名称,我希望将其反序列化为List<KeyValuePair<string, string>>。直接使用以下代码无法成功:

JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json)

报错信息如下:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'1[System.Collections.Generic.KeyValuePair'2[System.String,System.String]]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

尝试把大括号替换为中括号会得到非法JSON,同样报错。想知道不需要自己写解析器的话有没有解决办法?

解决方法

核心思路是先利用JSON对象和字典的天然匹配关系,先反序列化为Dictionary<string, string>,再转换成目标列表:

// 先反序列化为字典
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
// 直接转换成List<KeyValuePair<string, string>>
var kvpList = dict.ToList();

这个方法完全不需要自定义解析逻辑,依赖Newtonsoft.Json的原生序列化能力和Linq扩展方法就能完成转换,简单高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:07:11