【发布时间】:2015-10-21 02:20:37
【问题描述】:
我在控制器的 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; }
}
【问题讨论】:
-
对你的帖子开头的一点建议meta.stackexchange.com/questions/2950/…我为你解决了这个问题
-
@Bongo 谢谢你
-
VB:我一般使用(New Script.Serialization.JavaScriptSerializer).Deserialize(Of Students())(StudentJSONString)。只要您的学生类有 Name/Registered/StudentNo 属性,这应该可以工作
-
你的 StudentNo 是一个整数吧?
-
Debug.Write 会给你这个确实是正确的输出
标签: c# json asp.net-mvc dictionary