2016-04-24 35 views
0

我具有平坦DTO这样的Json净序列扁平物体到一个复杂的对象(变化对序列化/反序列化对象结构)

public class User 
{ 
    [JsonProperty("email")] 
    public string Email { get; set; } 

    [JsonProperty("fname")] 
    public string FirstName { get; set; } 

    [JsonProperty("lname")] 
    public string LastName { get; set; } 

    [JsonProperty("phone")] 
    public string Phone { get; set; } 

    [JsonProperty("city")] 
    public string City { get; set; } 

    [JsonProperty("country")] 
    public string CountryCode { get; set; } 

    [JsonProperty("state")] 
    public string State { get; set; } 

    [JsonProperty("zip")] 
    public string Zip { get; set; } 

    [JsonProperty("address1")] 
    public string Address1 { get; set; } 

    [JsonProperty("address2")] 
    public string Address2 { get; set; } 
} 

这是默认在一个“平面” JSON序列:

{ 
    'email':'[email protected]', 
    'fname':'John', 
    'phone':'123456789', 
    'city':'New York', 
    'zip':'1111', 
    'lname':'Joe', 
    'state':'NY', 
    'address1' : 'address1' 
} 

我想序列化,以更结构化JSON对象:

{ 
    'email':'[email protected]', 
    'fname':'John', 
    'phone':'123456789', 
    'lname':'Joe', 
    'address' : { 
     'city':'New York', 
     'zip':'1111',   
     'state':'NY', 
     'address1' : 'address1' 
     }   
} 

有什么办法做到这一点,而不创建一个自定义的JsonConverter?

回答

3

不,没有自定义的JsonConverter,或者没有通过引入合适的Address类别来推广平面模型,没有办法做到这一点。

+0

那么,它也可以与[定制contractresolver](http://www.newtonsoft.com/json/help/html/contractresolver.htm) - 但这将是更多的工作。 – dbc