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

如何用.NET System.Text.Json将JSON对象数组反序列化为C# Dictionary?

问题:将JSON对象数组反序列化为单个Dictionary<string, string>

原始JSON内容:

{"TestObjects": [{"the": "goal"},{"is": "to"},{"deserialize": "this"},{"simple": "array"},{"of": "objects"},{"into": "a"},{"C#": "Dictionary"}]}

我需要用.NET的System.Text.Json,把上述JSON中TestObjects数组里的每个仅含一对键值的对象,合并反序列化为一个Dictionary<string, string>类型的属性。

现有实现

目前我已经能将其反序列化为Dictionary<string, string>[](每个对象对应一个独立字典),代码示例如下:

public class TestClass
{
    public Dictionary<string, string>[] TestObjects { get; set; }
}

var stream = File.OpenRead(@"C:\test\test.json");

TestClass result = JsonSerializer.Deserialize<TestClass>(stream);

但我的目标是让TestObjects属性的类型是Dictionary<string, string>,而非数组类型。


更新 - 解决方案
我找到了多个可行方案,最终采用修改JSON格式的方案,修改后的JSON可直接反序列化为单个字典:

{"TestObjects": {"the": "goal","is": "to","convert": "this","simple": "array","of": "objects","into": "a","C#": "Dictionary"}}

注:如果JSON格式无法修改(比如是网络接口返回的内容),其他方案同样适用,本次因可手动编辑JSON,所以选择了这个最直接的方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:11