Deserialize JSON string to .NET object Collection

Dec 8, 2009 at 5:37 AM

Hello,

I have the json string as

string json = {
    "errorText": "",
    "count": 2,
    "indexFirst": 1,
    "indexLast": 2,
    "timeZoneRules": null,
    "people": [
        {
            "sID": "ABC1234",
            "city": "Kansas city",

            "zipcode": "50202",

            "nameFirst": "Brook"           

            "hashcode": "09uadsfDFDAFD",
            
        },
        {
            "sID": "XYZ1234",
            "city": "Detroit",
            "zipcode": "01010",

            "nameFirst": "Steve",
            "hashcode": "iue9484399reD",           
        }
    ],
    "emails": null,
    "searchType": "managerSID",
    "fetchTime": 0.016,
    "queryTime": 0.156
}

 

Since I need only userID & nameFirst values from the json, I created the people class with only two properties

public class people
    {
        private string _userId;
        private string _nameFirst;

        
        public string userID
        {
            get
            {
                return _userId;
            }
            set
            {
                _userId = value;
            }
        }
       
        public string nameFirst
        {
            get
            {
                return _nameFirst;
            }
            set
            {
                _nameFirst = value;
            }
        }

        
    }

 

and doing the deserialization as

 

List<people> peopleCollection = JsonConvert.DeserializeObject <List<people>>(json);           //string json -- >holds the json value

 

I am getting the error as

 

Expected a JsonObjectContract or JsonDictionaryContract for type 'System.Collections.Generic.List`1[WebApplication4.people]', got 'Newtonsoft.Json.Serialization.JsonArrayContract'.

 

Can anyone hint me on where I am making mistake.  in order to deserialize json to .net object, Should the people class should have properties of all that is in the people array in json string?

Thanks, Pete

Dec 22, 2009 at 5:19 PM

I had the same problem.

I solved it by creating another class for the collection element.

Eg.

public class peoplecollection
    {
        private List<people> _peoples;
        
        public List<people> Peoples
        {
            get
            {
                return __peoples;
            }
            set
            {
                __peoples= value;
            }
        }

Then deserialize into peoplecollection class instead.

peopleCollection peopleGroup = JsonConvert.DeserializeObject <peopleCollection>(json);   

Give it a try. It worked for me.

Kevin