gpt4 book ai didi

C# 扁平化 json 结构

转载 作者:IT王子 更新时间:2023-10-29 04:38:28 30 4
gpt4 key购买 nike

我在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com