JSON映射到对象不是1对1

本文关键字:对象 映射 JSON | 更新日期: 2023-09-27 18:14:42

我试图将JSON响应反序列化为不映射1到1的对象。我要反序列化的JSON是

{
"CustomerID": "1",
"CustomerName": "John Doe",
"BillingAddressLine1": "1234 Main St",
"BillingAddressLine2": "APT. 5",
"BillingCity": "New York City",
"BillingState": "NY",
"BillingZip": "12345",
"BillingCountry": "USA",
"BillingAttention": "John Doe",
"MailingAddressLine1": "555 Main St",
"MailingAddressLine2": "P.O. Box 5",
"MailingCity": "New York City",
"MailingState": "NY",
"MailingZip": "12345",
"MailingCountry": "USA",
"MailingAttention": "Jane Doe"  
}

而我要反序列化的对象是

public class Customer
{
    public int CustomerID{ get; set;}
    [JsonProperty(PropertyName = "CustomerName")]
    public string Name {get; set;}
    public Address BillingAddress{get; set;}
    public Address MailingAddress{get; set;}
}
public class Address
{
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
    public string Attention { get; set; }
}

是否有一种方法可以通过使用Newtonsoft JSON反序列化器来映射,或者这需要一个自定义的映射函数?

JSON映射到对象不是1对1

nair,

  1. 首先,最好使用http://json2csharp.com/与Json一对一生成对象。

  2. 调用第二个方法将Json-like-object解析为你的对象

简单,有点不太好,但保留KISS…