c# 反序列化对象错误的 JSON 列表
当我反序列化到对象列表时它可以工作,但是当我反序列化到具有列表类型的对象时它会出错。知道如何让它发挥作用吗?
页面名称: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”类型,不能在此通用集合中使用。
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?
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);
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议做这样的事情:
并将构造函数更改为:
您不必担心类型之间的混乱转换,而且它也可以正常工作,因为您的 People 类有一个接受 IEnumberable 的基本构造函数。
I would suggest doing something like this:
and changing your constructor to this:
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.