首页 > 解决方案 > C# 对象到 json 映射

问题描述

我有个问题:

我想将以下 C# 对象映射到 json 结构:

public class TestObj{
        [JsonProperty("full_name")]
        public string Name{ get; set; }


        public City City{ get; set; } = new City();
}

public class City{
        [JsonProperty("city_name")]
        public string Name{ get; set; }
        [JsonProperty("zip")]
        public string ZIP{ get; set; }
        [JsonProperty("country")]
        public string Country{ get; set; }
}

我希望 json 看起来像这样:

{
  "full_name": "abx",
  "zip": "xyz",
  "country":"xxx",
  "city_name":"bb"
}

我不希望城市成为 JSON 中的对象。我知道这不是最好的解决方案,但是我无法更改 json 的结构,因此我必须以这种特定方式映射对象。我可以以这种格式创建一个 jsonstring,但想问是否有人知道比使用 stringbuilder 更好的方法?

标签: c#json

解决方案


由于您正在谈论自定义结构而不仅仅是属性名称/可见性,您可能需要更改对象结构。这并不一定意味着您必须更改模型,而是可以将模型投影到专门用于序列化的结构中。

例如,您可能会像这样进行序列化:

var result = JsonConvert.SerializeObject(new {
    full_name = myObj.Name,
    zip = myObj.City.ZIP,
    country = myObj.City.Country,
    city_name = myObj.City.Name
});

如果这必须在多个地方完成,那么您可以通过将转换封装到模型上的方法中来避免重复逻辑,可能称为“ToSerializedObject”之类的方法。您可以为此创建一个特定的 DTO 对象,而不是使用匿名对象。所以总的来说可能是这样的:

public class TestObjDTO
{
    [JsonProperty("full_name")]
    public string Name{ get; set; }

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

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

    [JsonProperty("city_name")]
    public string CityName{ get; set; }
}

public class TestObj
{
    public string Name{ get; set; }

    public City City{ get; set; } = new City();

    public TestObjDTO ToSerializedObject()
    {
        return new TestObjDTO
        {
            Name = this.Name,
            ZIP = this.City.ZIP,
            Country = this.City.Country,
            CityName = this.City.Name
        };
    }
}

public class City
{
    public string Name{ get; set; }

    public string ZIP{ get; set; }

    public string Country{ get; set; }
}

然后你会这样使用它:

var result = JsonConvert.SerializeObject(myObj.ToSerializedObject());

基本上你可以随心所欲地安排它,但关键是这里最简单的路径可能只是创建你想要作为 DTO 的对象结构,而不是尝试自定义序列化程序来为你执行转换。


推荐阅读