2016-08-30 69 views
0

我使用Json.net api JsonConvert.PopulateObject它首先接受json字符串的兩個參數,然後接受要填充的實際對象。使用Json.net自定義反序列化屬性

,我想填充對象的結構

internal class Customer 
{ 

    public Customer() 
    { 
     this.CustomerAddress = new Address(); 
    } 
    public string Name { get; set; } 

    public Address CustomerAddress { get; set; } 
} 

public class Address 
{ 
    public string State { get; set; } 
    public string City { get; set; } 

    public string ZipCode { get; set; } 
} 

我的JSON字符串是

{ 
    "Name":"Jack", 
    "State":"ABC", 
    "City":"XX", 
    "ZipCode":"098" 
} 

現在Name財產得到填補,原因是其存在於JSON字符串,但CustomerAddress是沒有得到填充。有什麼辦法可以告訴Json.net庫,從City屬性填充CustomerAddress.City json字符串?

回答

1

直接 - 沒有。

但是應該可以實現這一點,例如,這裏是一個嘗試(假設你不能改變JSON):

class Customer 
{ 
    public string Name { get; set; } 
    public Address CustomerAddress { get; set; } = new Address(); // initial value 

    // private property used to get value from json 
    // attribute is needed to use not-matching names (e.g. if Customer already have City) 
    [JsonProperty(nameof(Address.City))] 
    string _city 
    { 
     set { CustomerAddress.City = value; } 
    } 

    // ... same for other properties of Address 
} 

其他可能性:

  • 變化JSON格式包含Address對象;
  • 自定義序列化(例如使用綁定器序列化類型並將其轉換爲需要);
  • ...(應該更多)。
相關問題