Json .Net将平面对象序列化为复杂的对象(在序列化/反序列化时更改对象结构) [英] Json .Net serialize flat object into a complex object (change objects structure on serialization/deserialization)

查看:75
本文介绍了Json .Net将平面对象序列化为复杂的对象(在序列化/反序列化时更改对象结构)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的扁平DTO

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

默认情况下,哪个序列化为'flat'JSON:

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

我想将其序列化为更结构化的JSON对象:

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

是否可以在不创建自定义JsonConverter的情况下做到这一点?

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

推荐答案

不,没有自定义的JsonConverter或通过引入适当的方法不适应 flat 模型的结构就无法做到这一点Address类.

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.

这篇关于Json .Net将平面对象序列化为复杂的对象(在序列化/反序列化时更改对象结构)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆