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