C#:从JsonObject/JsonNode提取字段转为List<Dictionary<string,string>>
异构JSON对象转List<Dictionary<string, string>>的解决方案
直接把JsonObject转成JSON字符串再反序列化为字典之所以失败,是因为数字、布尔、日期这类非字符串类型在JSON中没有引号,反序列化时会触发类型不匹配错误。正确的做法是遍历每个JSON对象的键值对,手动将每个值转为字符串。
基于System.Text.Json的实现(C#)
如果你的数据源是JsonNode数组:
using System.Text.Json.Nodes; using System.Collections.Generic; public List<Dictionary<string, string>> ConvertJsonNodeArray(List<JsonNode> jsonNodes) { var outputList = new List<Dictionary<string, string>>(); foreach (var node in jsonNodes) { if (node is not JsonObject jsonObj) continue; var stringDict = new Dictionary<string, string>(); foreach (var (key, value) in jsonObj) { // 统一将所有类型转为字符串,处理null值 stringDict[key] = value?.ToString() ?? string.Empty; } outputList.Add(stringDict); } return outputList; }
如果直接处理JsonObject数组:
using System.Text.Json.Nodes; using System.Collections.Generic; public List<Dictionary<string, string>> ConvertJsonObjectArray(List<JsonObject> jsonObjects) { var outputList = new List<Dictionary<string, string>>(); foreach (var obj in jsonObjects) { var stringDict = new Dictionary<string, string>(); foreach (var (key, value) in obj) { stringDict[key] = value?.ToString() ?? string.Empty; } outputList.Add(stringDict); } return outputList; }
注意事项
JsonNode.ToString()会自动处理各种类型的字符串转换:布尔值转为"True"/"False",日期转为ISO格式字符串,数字直接转为对应字符串- 若需要统一布尔值的大小写(比如转成小写"true"/"false"),可以针对布尔类型单独处理:
if (value is JsonValue jsonValue && jsonValue.TryGetValue<bool>(out bool boolVal)) { stringDict[key] = boolVal.ToString().ToLower(); } else { stringDict[key] = value?.ToString() ?? string.Empty; } - 对于嵌套的JSON对象/数组,如果需要展开处理,可以递归遍历
JsonNode的子节点
内容的提问来源于stack exchange,提问作者aarelovich
相关产品推荐
相关产品推荐

