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 に答える