首页 > 解决方案 > 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": [{}]
     }
]

标签: c#jsonserializationjson.netwebapi

解决方案


您可以一起删除该 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>();

推荐阅读