简体   繁体   中英

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?

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 .

I would suggest doing something like this:

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

and changing your constructor to this:

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

    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM