1

当我反序列化为对象列表时,它可以工作,但是当我反序列化为具有列表类型的对象时,它会出错。知道如何使它工作吗?

页面名称: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”类型,不能在此通用集合中使用

4

1 回答 1

6

我建议做这样的事情:

    People persons = new People(new JavaScriptSerializer().Deserialize<IList<Person>>(json));

并将您的构造函数更改为:

    public People(IEnumerable<Person> collection) : base(collection)
    {

    }

您不必担心类型之间的混乱转换,而且它也可以正常工作,因为您的 People 类有一个接受 IEnumberable 的基本构造函数。

于 2011-02-23T20:07:37.327 回答