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

标签 c# json

我有以下 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 为 null,我不明白为什么。

最佳答案

添加两个新类:

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

关于c# - 将嵌套的json对象反序列化为c#对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46561337/

相关文章:

javascript - 字符串化时间戳对象

json - Grails JSON编码

PHP json_decode 不起作用

c# - 制作异步方法的正确方法

c# - 如何使用先前输入的参数重新加载页面?

c# - 在 case 语句中使用冒号的 Razor 标记中的字符串切换导致错误 "unterminated string literal"

c# - 序列化名为 "return"的 JSON 对象

c# - Controller 未收到英国格式的 MVC3 日期

c# - Log4Net 与应用程序洞察

JavaScript 无法访问对象的属性