【问题标题】:How to deserialize in JSON.NET a list of objects with a nested list of objects? [duplicate]如何在 JSON.NET 中反序列化具有嵌套对象列表的对象列表? [复制]
【发布时间】:2017-09-24 02:19:09
【问题描述】:

我有这样的 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 对象反序列化的数组或列表。也可以将 JsonObjectAttribute 添加到类型中以强制它从 JSON 对象反序列化。

提前感谢您的帮助。

【问题讨论】:

  • 您的反序列化尝试不匹配,您的类名是Airplane,但您尝试反序列化为List&lt;Airport&gt;
  • 您的代码运行良好(如果您将 Airport 更改为 Airplane),可能是加载 json 出现问题。
  • 机场是飞机阵列吗?

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


【解决方案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; }
}

【讨论】:

  • 他已经有了他的 JSON 对象。
猜你喜欢
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多