c# Deserialize JSON list of object error

4.4k views Asked by At

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.

1

There are 1 answers

1
Daniel Ahrnsbrak On BEST ANSWER

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.