JSON映射到不是1到1的对象

时间:2013-05-20 14:09:58

标签: c# json deserialization json.net

我正在尝试将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反序列化器进行映射,还是需要自定义映射函数?

1 个答案:

答案 0 :(得分:0)

Nayr,

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

  2. 将Json解析为此对象。

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

  4. 简单,有点不太好,但保持KISS ......