繁体   English   中英

将嵌套的 json 对象反序列化为 c# 对象

[英]Deserialize nested json objects into c# objects

我有以下 Json 响应:

{
  "Customers": [
    {
      "Customer": {
        "Address": {
          "City": "Stockholm",
          "PostalCode": "10123"
        },
        "Classifications": [
          "LoyaltyProgram",
          "Returning",
          "VeryImportant"
        ],
        "FirstName": "Peter",
        "LastName": "Centers",
        "Passport": {
          "Expiration": "2019-01-14",
          "Number": "1564931321655"
        },
      },
      "FirstName": "Peter",
      "LastName": "Centers",
      "Reservation": {
        "AdultCount": 2,
        "AssignedSpaceId": "03f59360-8644-4e29-927a-ad85a6514466",
      },
      "RoomNumber": "302"
    },
  ]
}

我为每个客户提供以下课程:

public class CustomerDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<string> Classifications { get; set; }
    public PassportDto Passport { get; set; }
    public AddressDto Address { get; set; }
}

public class AddressDto
{
    public string City { get; set; }
    public string PostalCode { get; set; }
}

public class PassportDto
{
    public string Expiration { get; set; }
    public string Number { get; set; }
}

从此我使用 Json.Net 和我的一种方法(摘录)中的以下代码,其中下面的客户是响应:

var jsonCustomers = JObject.Parse(customers)["Customers"].Children().ToList();
IList<CustomerDto> customerList = new List<CustomerDto>();
foreach (var item in jsonCustomers) {
    customerList.Add(item.ToObject<CustomerDto>());
}

CustomerDto 中的所有值都被填充,除了 Address 和 Passport,它们都是空的,我不知道为什么。

添加两个新类:

public class CustomersWrapper
{
    public IEnumerable<CustomerWrapper> Customers { get; set; }
}

public class CustomerWrapper
{
    public CustomerDto Customer { get; set; }
}

然后将所有现有代码替换为:

        var results = JsonConvert.DeserializeObject<CustomersWrapper>(input);
        var customerList = results.Customers.Select(z => z.Customer).ToList();

这将确保对层次结构中的所有对象进行标准反序列化。

由于 JSON 的结构很奇怪,因此需要这样做。 https://stackoverflow.com/a/45384366/34092是相同的基本问题(可能值得一读) - 基本上你不应该在你的 JSON 中包含CustomersCustomer 如果没有这些,您将不需要我指定的两个包装类。

您可能还希望避免在 JSON 中两次(不必要地)指定FirstNameLastName

您可以创建一个包含客户列表的类:

public class CustomerList
{
    public IList<CustomerDto> Customers { get; set; }
}

而反序列化对象只需调用:

CustomerList jsonCustomers = JsonConvert.DeserializeObject<CustomerList>(customers);
IList<CustomerDto> customerList = jsonCustomers.Customers;

编辑:没有注意到 Customer 是 json 数组中对象列表上的嵌套属性,因此需要另一个包装CustomerDto类。 @mjwills 已经发布了完整的答案。

AddressDtoPassportDto不会被反序列化,因为您正在 JSON 图中的上一级反序列化。

写一个类,如:

public class WrapCustomer
{
        public CustomerDto Customer { get; set; }
}

然后在你的 for 循环中反序列化它:

customerList.Add(item.ToObject<WrapCustomer>());

现在您将看到一切都按您的预期填充。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM