展平嵌套的字典<字符串,对象> [英] Flatten nested Dictionary<string, object>

查看:208
本文介绍了展平嵌套的字典<字符串,对象>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我反序列化一些的嵌套JSON具有以下内容:

 字符串JSON = @{
    名:查理,
    someID:123,
    1级:{
        名:查理1,
        someID:456
    }
};

JavaScriptSerializer串行=新JavaScriptSerializer();
字典<字符串,对象>数据= serializer.Deserialize<字典<字符串,对象>>(JSON);
 

在此操作后,每个字典键的值可以是另一字典,依此类推,多级深

我想这样做的是扁平化的多层次的数据的所以它只是一个平面阵列/列表,只有所有的JSON属性名称和它们的值。所以,我最终的东西是这样的:

 的名字,查理
someID,123
名字,查理1
someID,456
 

我是标题下使用的路径的的SelectMany()的等等,但不能争吵它做什么我之后。

之类的,我一直在用这样的事情左右摇摆:

  VAR OBJ = data.Values​​.SelectMany<对象字典<字符串,对象>>(X => X);
 

但我不能够满足编译器。是的,我很失落。

我使用.NET 3.5。

解决方案

  Func键<字典<字符串,对象>中的IEnumerable< KeyValuePair<字符串,对象>>>扁平化= NULL;

扁平化=字典=> dict.SelectMany(KV =>
                        kv.Value是字典<字符串,对象>
                            ?扁平化((词典<字符串,对象>)kv.Value)
                            新名单,其中,KeyValuePair<字符串,对象>>(){} KV
                       );

变种flatList =弄平(数据).ToList();
 

I am deserializing some nested JSON with the following:

string json = @"{
    ""name"": ""charlie"",
    ""someID"": 123,
    ""level1"" : {
        ""name"": ""charlie 1"",
        ""someID"": 456
    }
}";

JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> data = serializer.Deserialize<Dictionary<string, object>>(json);

Once this is done, the values of each dictionary key may be another Dictionary, and so on, multiple levels deep.

What I would like to do is to flatten the multi-level data so it's just a flat Array/List, with just all the JSON attribute names and their values. So that I end up with something like this:

name, "charlie"
someID, 123
name, charlie 1
someID, 456

I was heading down the path of using SelectMany() and so forth, but could not wrangle it to do what I am after.

I've been sort of waddling around with things like this:

var obj = data.Values.SelectMany<object, Dictionary<string, object>>(x => x);

But I am not able to satisfy the compiler. Yes, I am lost.

I am using .NET 3.5.

解决方案

Func<Dictionary<string, object>, IEnumerable<KeyValuePair<string, object>>> flatten = null;

flatten = dict => dict.SelectMany(kv => 
                        kv.Value is Dictionary<string,object> 
                            ? flatten((Dictionary<string,object>)kv.Value)
                            : new List<KeyValuePair<string,object>>(){ kv}
                       );

var flatList = flatten(data).ToList();

这篇关于展平嵌套的字典&LT;字符串,对象&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆