且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#扁平化的JSON结构

更新时间:2022-10-14 17:53:31

  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.