C# 扁平化 json 结构

标签 c# json data-structures recursion

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

{
    "name": "test",
    "father": {
         "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().Where(p => !p.HasValues);
Dictionary<string, string> results = jTokens.Aggregate(new Dictionary<string, string>(), (properties, jToken) =>
                    {
                        properties.Add(jToken.Path, jToken.ToString());
                        return properties;
                    });

我有将嵌套的 json 结构扁平化为字典对象的相同要求。找到解决方案 here .

关于C# 扁平化 json 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7394551/

相关文章:

c# - 在 UWP 应用程序中制作向导的正确方法?

c# - 使用 Lambda 从 Expression 获取集合的值 - .Contains

c# - 我如何在 XNA 4.0 中使用搅拌器动画?

javascript - 如何将数组列表格式化为json

Java - 将对象移动到LinkedList的前面

algorithm - 从大量条目中随机详尽(非重复)选择

c# - 使用 Alphavss 的卷影复制错误

java - 点的 JsonPath JUnit 转义字符

jquery - JSON数据不显示在网页上

algorithm - 插入缩写词