如何在JSON.NET中反序列化具有嵌套对象列表的对象列表?

时间:2017-04-26 15:18:03

标签: c# json serialization json.net json-deserialization

我有这样的json文件。

[
  {
    "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"
  }
]

飞机清单:

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; }
}

嵌套的成员列表。

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

我不知道如何反序列化此文件。 我试着这么做......

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

但它没有用。

Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'lab7.Airport',因为该类型需要JSON数组(例如[1,2,3] )正确反序列化。 要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用此网站生成课程:JSON to C#

导致此代码:

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; }
}