C#反序列化对象错误的JSON列表 [英] c# Deserialize JSON list of object error
问题描述
当我反序列化到对象列表时,它可以工作,但是当我反序列化到具有列表类型的对象时,它会出错.知道如何使它起作用吗?
when I deserialize to list of object it work but when I deserialize to a object with list type it errors out. Any idea how to make it work?
页面名称:testjson.aspx
page name: 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);
}
}
错误消息: 值"System.Collections.Generic.Dictionary`2 [System.String,System.Object]"的类型不是"JSON.Person",因此无法在该通用集合中使用..
Error message: The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "JSON.Person" and cannot be used in this generic collection.
推荐答案
我建议这样做:
People persons = new People(new JavaScriptSerializer().Deserialize<IList<Person>>(json));
并将您的构造函数更改为此:
and changing your constructor to this:
public People(IEnumerable<Person> collection) : base(collection)
{
}
您不必担心类型之间的混乱转换,它也一样好,因为您的People类具有一个采用IEnumberable的基本构造函数.
You don't have to worry about messy casts between types, and it works just as well since your People class has a base constructor that takes in an IEnumberable.
这篇关于C#反序列化对象错误的JSON列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!