我如何解析这个Json:
[{
"value": "",
"date": {
"value": "17/04/2015"
},
"hour": {
"value": "21:00"
},
"venue": {
"value": "some stadium."
}}, {
"value": "",
"date": {
"value": "18/04/2015"
},
"hour": {
"value": "20:30"
},
"venue": {
"value": "some stadium"
}}]
我试过这段代码:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
foreach (var item in serializer.Serialize(item.dates))
{
@* item == "34 ''" *@
}
但它的返回字符串" 34''"而是我想要的。
有人能帮助我理解我错过了什么吗? 感谢答案 0 :(得分:4)
您应该使用DeserializeObject
- 方法而不是Serialize
- 方法。
它返回一个对象[],其中包含Dictionary<string, object>
- 元素(您的数据)
要从数组中获取值,请将当前Item转换为Dictonary<string, object>
(表示json对象)并使用索引器访问该值。
示例:
var v = new JavaScriptSerializer();
var arr = (object[]) v.DeserializeObject(File.ReadAllText("json.txt"));
for (var i = 0; i < arr.Length; i++)
{
Console.WriteLine(((Dictionary<string, object>)arr[i])["value"]);
}
示例2 - 访问日期对象内的值:
var v = new JavaScriptSerializer();
var arr = (object[])v.DeserializeObject(File.ReadAllText("json.txt"));
for (var i = 0; i < arr.Length; i++)
{
// The current object
var c = (Dictionary<string, object>) arr[i];
// Getting the date object
var date = (Dictionary<string, object>) c["date"];
// Printing the value inside of the date object
Console.WriteLine(date["value"]);
// OUTPUT:
// 17/04/2015
// 18/04/2015
}