1

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 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! I spent a good deal of time trying to figure out how to deserialize my custom object before I found your post. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.