更新时间:2022-10-14 17:44:03
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.