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

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

问题描述

我在C#中有一个json对象(表示为Newtonsoft.Json.Linq.JObject对象),我需要将其压缩到一个字典。让我给大家介绍一下我的意思:

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

这应该产生一个包含以下内容的字典键值对:

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

我该怎么做?

解决方案

  JObject jsonObject = JObject.Parse(theJsonString); 
IEnumerable< JToken> jTokens = jsonObject.Descendants()。其中​​(p => p.Count()== 0);
字典< string,string> result = jTokens.Aggregate(new Dictionary< string,string>(),(properties,jToken)=>
{
properties.Add(jToken.Path,jToken.ToString());
return property;
});

我将嵌套的json结构平铺到字典对象上有同样的要求。找到解决方案此处


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天全站免登陆