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

帅比萌擦擦* 提交于 2019-12-12 02:26:09

问题


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 ?


回答1:


No, there's no way to do this without a custom JsonConverter, or without adpating the structure of your flat model by introducing a proper Address class.



来源:https://stackoverflow.com/questions/36822468/json-net-serialize-flat-object-into-a-complex-object-change-objects-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!