1 c# serialization json javascriptserializer
当我反序列化它的工作列表时,但是当我反序列化为具有列表类型的对象时,它会出错.知道如何让它工作吗?
页面名称:testjson.aspx
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace Web.JSON
{
public partial class testJson : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string json = "[{\"SequenceNumber\":1,\"FirstName\":\"FN1\",\"LastName\":\"LN1\"},{\"SequenceNumber\":2,\"FirstName\":\"FN2\",\"LastName\":\"LN2\"}]";
//This work
IList<Person> persons = new JavaScriptSerializer().Deserialize<IList<Person>>(json);
//This error
//People persons = new JavaScriptSerializer().Deserialize<People>(json);
Response.Write(persons.Count());
}
}
class Person
{
public int SequenceNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class People : List<Person>
{
public People()
{
}
public People(IEnumerable<Person> init)
{
AddRange(init);
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息:值"System.Collections.Generic.Dictionary`2 [System.String,System.Object]"不是"JSON.Person"类型,不能在此通用集合中使用.
我建议做这样的事情:
People persons = new People(new JavaScriptSerializer().Deserialize<IList<Person>>(json));
Run Code Online (Sandbox Code Playgroud)
并将构造函数更改为:
public People(IEnumerable<Person> collection) : base(collection)
{
}
Run Code Online (Sandbox Code Playgroud)
您不必担心类型之间的混乱转换,并且它也可以正常工作,因为您的People类具有一个接受IEnumberable的基础构造函数.