c# - C# WebApi - Json 序列化将属性提升到更高级别
问题描述
我有一个具有以下结构的类
class Model
{
public int Id {get;set;}
public Dictionary<string, List<ComplexType>> Values {get;set;}
}
在 Dotnetcore webApi 项目中使用并从我的控制器返回为以下对象
Ok(new List<Model>() {
new Model{
Id = 1,
Values = new Dictionary<string, List<ComplexType>>() { {"Item1", new List<ComplexType>()} }
} } )
这将产生 Json 输出为:
[
{
"Id": "1"
"Values": {
"Item1": [{}]
}
}
]
所以我的问题是任何可能的方式,将 Dictionary 属性名称带到输出 Json 结构中的更高级别。基本上在“模型”类中省略属性名称“值”并合并较低的对象,所以它看起来像这样:
[
{
"Id": "1"
"Item1": [{}]
}
]
解决方案
您可以一起删除该 Value 属性并使 Model 成为字典类型
class Model : Dictionary<string, List<ComplexType>>
{
public int Id { get; set; }
}
那么你可以做
var model = new Model();
model.Id = 123;
model["Item1"] = new List<ComplexType>();
推荐阅读
- flutter - Flutter Web:使用它构建 Web 应用程序的副作用是什么
- c++ - 如何在给定的字符串中找到一个字母序列?
- react-native - 如何在 React Native 上创建具有多种背景颜色的图表
- python - 列上的 pandas MultiIndex 从级别 0(外部)和级别 1(内部)中选择列
- javascript - VueJs 相应地更新选择框
- spring-cloud-dataflow - Spring Cloud Data Flow 中子任务的重复端口
- javascript - 您可以以编程方式显示数据列表下拉列表吗?
- html - 将 POST 请求中的工作表单数据转换为 Postman 请求
- python - 如何使用 SQLAlchemy 从 Linux 主机对 SQL Server 使用 Windows 身份验证?
- html - 组件交互 2 向角度