C# 中如何将自定义JSON反序列化为Dictionary<string, string>?
实现方案
核心思路
先解析JSON获取顶层Values节点,遍历节点下所有属性,对属性值做类型判断:字符串类型直接取值,对象/其他复杂类型直接序列化为JSON字符串作为字典值,最终组装为目标Dictionary<string, string>即可,无需提前定义适配JSON结构的Model类。
代码实现
基于Newtonsoft.Json(Json.NET)实现
适用于全版本.NET平台,需提前安装Newtonsoft.Json NuGet包:
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; // 输入的JSON字符串 string inputJson = @" { ""Values"": { ""Value1"":""XXX"", ""value2"" : { ""SubValue1"":""YX"", ""SubValue2"":""AB"" } } }"; Dictionary<string, string> resultDict = new Dictionary<string, string>(); JObject rootObj = JObject.Parse(inputJson); JObject valuesNode = rootObj["Values"] as JObject; foreach (var prop in valuesNode.Properties()) { string key = prop.Name; // 若需要和示例一致将value2转为Value2,取消下方注释即可 // key = char.ToUpper(key[0]) + key[1..]; string value = prop.Value.Type == JTokenType.String ? prop.Value.ToString() : prop.Value.ToString(Formatting.Indented); resultDict.Add(key, value); }
基于System.Text.Json实现
.NET Core 3.0/.NET 5+ 自带的官方JSON库,无需安装第三方依赖:
using System.Collections.Generic; using System.Text.Json; // 输入的JSON字符串 string inputJson = @" { ""Values"": { ""Value1"":""XXX"", ""value2"" : { ""SubValue1"":""YX"", ""SubValue2"":""AB"" } } }"; Dictionary<string, string> resultDict = new Dictionary<string, string>(); using JsonDocument jsonDoc = JsonDocument.Parse(inputJson); JsonElement valuesNode = jsonDoc.RootElement.GetProperty("Values"); foreach (var prop in valuesNode.EnumerateObject()) { string key = prop.Name; // 若需要和示例一致将value2转为Value2,取消下方注释即可 // key = char.ToUpper(key[0]) + key[1..]; string value = prop.Value.ValueKind == JsonValueKind.String ? prop.Value.GetString() : JsonSerializer.Serialize(prop.Value, new JsonSerializerOptions { WriteIndented = true }); resultDict.Add(key, value); }
注意事项
- 嵌套对象的输出格式可自行调整:不需要缩进的话将
Formatting.Indented改为Formatting.None(Newtonsoft.Json),或者将WriteIndented设为false(System.Text.Json) - 若存在数组类型的属性值,上述逻辑也会自动将数组序列化为JSON字符串作为字典值,适配扩展场景
内容的提问来源于stack exchange,提问作者Sandro
相关产品推荐
相关产品推荐

