使用foreach循环将数据反序列化到字典
本文关键字:反序列化 字典 数据 foreach 循环 使用 | 更新日期: 2023-09-27 18:05:30
我在控制器中的c# MVC应用程序中发生了以下事情:
Dictionary<string, string> dictionaryList = new Dictionary<string, string>();
getJsonData data = new JavaScriptSerializer().Deserialize<getJsonData>(System.IO.File.ReadAllText(json_file_path));
foreach (var item in data.students)
{
dictionaryList.Add("Student Name: ", item.studName);
dictionaryList.Add("Student Number: ", item.studNumb);
dictionaryList.Add("Registered: ", item.registered);
Debug.Write(dictionaryList);
}
首先在我的DebugConsole我得到
System.Collections.Generic.Dictionary`2[System.String,System.String]
代替值
在第二次迭代时抛出异常
Exception thrown: 'System.ArgumentException' in mscorlib.dll
我知道第二次迭代抛出异常,因为dictionaryList一次只能有一个唯一的键,但通过论坛,我对如何实现一些解决方案感到有点困惑。如果我删除字典和Debug.Write(data.jobs);
,代码正常运行,但如果它是字典格式,则更容易将数据移动到HTML表中。
我不能使用
List<Students> = JsonConvert.DeserializeObject<getJsonData>(System.IO.File.ReadAllText(json_file_path));
因为我的json文件的格式是
{
"students": [{
"Name" : "Robert Mcguffin",
"Registered" : "2014-07-20 05:34:16",
"StudentNo:" : 1
} , {
"Name" : "Agathe Dubois",
"Registered" : "2014-05-30 09:46:26",
"StudentNo:" : 2
} , {
"Name" : "Steven Corral",
"Registered" : "2015-02-11 09:58:16",
"StudentNo:" : 3
}]
}
,由于某些原因,JsonConvert无法识别
我真的很想知道如何使用foreach循环将我的数据放入字典。
谢谢。
public class getJsonData
{
public List<Students> students { get; set; }
}
public class students
{
public string studName { get; set; }
public string studNumb { get; set; }
public string registered { get; set; }
}
从您提供的示例中,我看到了一些问题。首先,StudentNo的JSON包含一个":",这可能会在反序列化时导致一些问题,所以我建议你删除这些。
我尝试了你的例子,并改变了一点。DataTable应该很容易融入到您的项目中,因为Dictionary并不是最好的选择。
public static DataTable DoSomething()
{
DataTable table = new DataTable();
table.Columns.Add("Student Name");
table.Columns.Add("Student Number");
table.Columns.Add("Registered");
getJsonData data = new JavaScriptSerializer().Deserialize<getJsonData>(System.IO.File.ReadAllText(@"C:'Users'mailb_000'Downloads'texts'test.json"));
foreach (var item in data.students)
{
table.Rows.Add(item.Name, item.StudentNo, item.registered);
Debug.Write(table);
}
return table;
}
public class getJsonData
{
public List<students> students { get; set; }
}
public class students
{
public string Name { get; set; }
public int StudentNo { get; set; }
public string registered { get; set; }
}
顺便说一句。既然你写你想要一个HTML表,我想这个链接应该帮助你数据表到html表