C#扁平化的JSON结构 [英] C# flattening json structure

查看:345
本文介绍了C#扁平化的JSON结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的JSON对象(表示为Newtonsoft.Json.Linq.JObject对象),我需要把它压扁字典。让我告诉你我的意思的例子:

  {
名:测试,
父亲:{
名:test2的
时代:13,
狗:{
色:棕色
}
}
}

这应该产生一个字典,以下键 - 值对:

  [名称] ==测试,
[father.name ] ==测试2,
[father.age] == 13,
[father.dog.color] ==棕色

我怎样才能做到这一点?


解决方案

  JObject的JSONObject = JObject.Parse(theJsonString); 
IEnumerable的< JToken> jTokens = jsonObject.Descendants()式。(P => p.Count()== 0);
&字典LT;字符串,字符串>结果= jTokens.Aggregate(新词典&下;串,串GT;(),(属性,jToken)= GT;
{
properties.Add(jToken.Path,jToken.ToString());
返回性能;
});



我有一个扁平化嵌套JSON结构,Dictionary对象的同样的要求。找到了解决办法这里


I have a json-object in C# (represented as a Newtonsoft.Json.Linq.JObject object) and I need to flatten it to a dictionary. Let me show you an example of what I mean:

{
    "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"

How can I do this?

解决方案

JObject jsonObject=JObject.Parse(theJsonString);
IEnumerable<JToken> jTokens = jsonObject.Descendants().Where(p => p.Count() == 0);
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.

这篇关于C#扁平化的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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