2016-08-30 67 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对象;
  • 自定义序列化(例如使用绑定器序列化类型并将其转换为需要);
  • ...(应该更多)。
相关问题