[英]Convert a json (with many levels) into a List c#
我有一个 JSON 里面有很多级别,如下所示
{
"value": [
{
"CityId": 100
"Colleges": {
"CollegeName": "ABC",
"Departments": [
{
"DepartmentId": 1001,
"DepartmentInfo": {
"Name": "ComputerScience",
"StudentsCount": 60,
"HOD": "John"
}
},
{
"DepartmentId": 1002,
"DepartmentInfo": {
"Name": "Humanties",
"StudentsCount": 120,
"HOD": "Ravi"
}
}
]
}
},
{
"CityId": 100
"Colleges": {
"CollegeName": "DEF",
"Departments": [
{
"DepartmentId": 2001,
"DepartmentInfo": {
"Name": "ComputerScience",
"StudentsCount": 60,
"HOD": "James"
}
},
{
"DepartmentId": 2002,
"DepartmentInfo": {
"Name": "Humanties",
"StudentsCount": 120,
"HOD": "Donald"
}
}
]
}
}
]
}
我已经获取了 CollegeInfo、DepartmentId、Name、StudentsCount、HOD 等信息。 所以我用这些属性创建了 class。
现在从下面的代码中,我可以获取 Dictionary<string, object> 中的所有信息。 这里的 Key 是 JSON 内属性的路径。
private static void FillDictionaryFromJToken(Dictionary<string, object> dict, JToken token, string path = "")
{
switch (token.Type)
{
case JTokenType.Object:
foreach (JProperty prop in token.Children<JProperty>())
{
FillDictionaryFromJToken(dict, prop.Value, prop.Path);
}
break;
case JTokenType.Array:
foreach (JToken value in token.Children())
{
FillDictionaryFromJToken(dict, value);
}
break;
default:
dict.Add(path, ((JValue)token).Value);
break;
}
}
现在第一组的所有属性都是单独的记录,第二组也是如此。 路径将像这样 [0].Colleges.Departments[0].DepartmentId、Colleges.Departments[0].DepartmentInfo.Name 等。但我想将 class 中的这些信息作为单个记录填写,其中的所有属性该记录与第二组相同。
有什么帮助吗??
您可以尝试使用 package Newtonsoft.Json,并使用代码:
YourClassWithTheProperties instance =
JsonConvert.Deserialize<YourClassWithTheProperties>(jsonString);
这样做您将拥有一个 class 并且您可以在属性中使用 foreach。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.