我在C#中有一个json对象(表示为Newtonsoft.Json.Linq.JObject对象),我需要将其展平到字典.让我举一个例子来说明我的意思:

{
    "name": "test",
    "father": {
         "name": "test2"
         "age": 13,
         "dog": {
             "color": "brown"
         }
    }
}

This should yield a dictionary with the following key-value-pairs:

["name"] == "test",
["father.name"] == "test2",
["father.age"] == 13,
["father.dog.color"] == "brown"

我该怎么做?

推荐答案

JObject jsonObject=JObject.Parse(theJsonString);
IEnumerable<JToken> jTokens = jsonObject.Descendants().Where(p => !p.HasValues);
Dictionary<string, string> results = jTokens.Aggregate(new Dictionary<string, string>(), (properties, jToken) =>
                    {
                        properties.Add(jToken.Path, jToken.ToString());
                        return properties;
                    });

I had the same requirement of flattening a nested json structure to a dictionary object. Found the solution here.

Json相关问答推荐

时间和日期数据绘制不正确

当有2个嵌套数组时展平复杂的JSON

无法从MongoDB集合中检索正确的文档

创建Json嵌套文件 struct

bash用jq获取第二条JSON记录

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

将 json 转换为 jsonb 安全吗?

基于JQ中另一个对象的值 Select 对象

遍历 JSON,检索父值

jq EOF 处的无效数字文字将 json 值更新为 0.0.x

使用 jq 和脚本 bash 映射两个 json

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

如何配置spring mvc 3在json响应中不返回null对象?

以 JSON 格式访问(新型、公共)Google 工作表

使用 boost 属性树读取 int 数组

在 JavaScript 中从 Json 数据中删除反斜杠

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何在 Java 中将 YAML 转换为 JSON?

将多个值存储在json中的单个键中

Laravel 5 控制器将 JSON 整数作为字符串发送