简体   繁体   中英

Json .Net serialize flat object into a complex object (change objects structure on serialization/deserialization)

I have a flat DTO like this

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; }
}

Which is by default serialized in to a 'flat' JSON:

{
     'email':'john@doe.net',
     'fname':'John',
     'phone':'123456789',
     'city':'New York',
     'zip':'1111',
     'lname':'Joe',
     'state':'NY',
     'address1' : 'address1'
}

I would like to serialize it to more structured JSON object:

{
     'email':'john@doe.net',
     'fname':'John',
     'phone':'123456789',
     'lname':'Joe',
     'address' : {
         'city':'New York',
         'zip':'1111',         
         'state':'NY',
         'address1' : 'address1'
      }         
}

Is there any way to do it without creating a custom JsonConverter ?

不,没有自定义JsonConverter或通过引入适当的Address类来适应平面模型的结构,是无法做到这一点的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM