我想將JSON反序列化爲List。我有.NET 4.0。正常的反序列化到一個對象工作正常。我是C#中的絕對初學者。無法將JSON反序列化到C#4.0中的列表中
我在各種論壇的幫助下寫了下面的代碼。當我嘗試將反序列化的JSON加載到Lad類型的List中時,它不會給出任何錯誤,但是當我檢查Lads對象時,它只是空白。
using System;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace RESTServicesJSONParserExample
{
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string firstName { get; set; }
public string lastName { get; set; }
public MyDate dateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
//This fails to load desereialized JSON in the List
List<Lad> Lads = new JavaScriptSerializer().Deserialize<List<Lad>>(json);
Lad Lad1 = new JavaScriptSerializer().Deserialize<Lad>(json);
Console.WriteLine(Lad1.firstName);
//Nothing returned here
foreach (Lad Lad2 in Lads)
{
Console.WriteLine(Lad2.firstName);
}
Console.ReadLine();
}
}
}
工作!並感謝超級快速的迴應和解釋。 – cyboashu