Search code examples
c#jsonserializationjson.netjson-deserialization

How to deserialize in JSON.NET a list of objects with a nested list of objects?


I have json file like this.

[
  {
    "listMember": [
      {
        "Name": "Cris",
        "Position": "Командир",
        "Age": 50,
        "Experience": 25
      },
      {
        "Name": "Sandra",
        "Position": "Стюардесса",
        "Age": 25,
        "Experience": 5
      }
    ],
    "Id": 31004,
    "Type": "грузовой",
    "Model": "Bell",
    "Year_of_issue": 2007,
    "Seats": 150,
    "Carrying": 50,
    "Maintenance": "12.04.2017"
  }
]

List of airplane:

class Airplane
    {
        public List<Member> listMember = new List<Member>();
        public Int16 Id { get; set; }
        public String Type { get; set; }
        public String Model { get; set; }
        public Int16 Year_of_issue { get; set; }
        public Int16 Seats { get; set; }
        public Int16 Carrying { get; set; }
        public String Maintenance { get; set; }
}

Nested List of members.

class Member
{
    public string Name { get; set; }
    public string Position { get; set; }
    public UInt16 Age { get; set; }
    public UInt16 Experience { get; set; }
}

I have no idea how to deserialize this file. I tried to do so...

List<Airport> airport = JsonConvert.DeserializeObject<List<Airport>>(json);

But it is not working.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'lab7.Airport' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Thanks in advance for your help.


Solution

  • You can generate your classes with this website: JSON to C#

    It results in this code:

    public class ListMember
    {
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public int Experience { get; set; }
    }
    
    public class RootObject
    {
        public List<ListMember> listMember { get; set; }
        public int Id { get; set; }
        public string Type { get; set; }
        public string Model { get; set; }
        public int Year_of_issue { get; set; }
        public int Seats { get; set; }
        public int Carrying { get; set; }
        public string Maintenance { get; set; }
    }