c# - 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 更好的方法?
解决方案
由于您正在谈论自定义结构而不仅仅是属性名称/可见性,您可能需要更改对象结构。这并不一定意味着您必须更改模型,而是可以将模型投影到专门用于序列化的结构中。
例如,您可能会像这样进行序列化:
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 的对象结构,而不是尝试自定义序列化程序来为你执行转换。
推荐阅读
- javascript - 传递变量以形成动作 javascript 和 HTML
- ios - 如何在 Bar 按钮项上放置标签?
- php - 从 Sendy API 获取活动订阅者计数时出错
- javascript - 回调不调用
- node.js - 如何默认返回错误作为 JSON 而不是 HTML 与 express?
- javascript - 如何在 Dropzone.js 中更改图像上传顺序
- javascript - 如何检查数组中的特定对象(数据)?
- android - Xamarin Android 使用 Camera2 API,需要执行自动对焦。
- r - 结合 data.table 中的合并执行“模糊连接”(和非模糊连接)
- spring - 不可解析的父 POM:来自 https://repo.spring.io/snapshot 的 1.5.17.BUILD-SNAPSHOT