ASP.NET Core中如何定义接收未知属性JSON的POST请求模型?
问题描述
我需要接收来自ag-grid getFilterModel()方法返回的JSON数据,结构如下:
{ property1: { type: "string", values: ["test1", "test2"] }, property2: ... (其他类似结构的属性) }
这些JSON的属性名称不确定,但所有属性的值都是GenericProperty类型。目前我通过硬编码定义MyTestObject类来接收数据,但需要逐个列出所有可能的属性,非常繁琐。现有代码如下:
POST接口代码
[HttpPost] public void testAPI(MyTestObject test){ // 处理逻辑 }
MyTestObject.cs
public class MyTestObject{ public GenericProperty heights {get; set;} ; public GenericProperty weights {get; set;} ; // 所有属性都是GenericProperty类型,但不想逐个显式定义 }
GenericProperty.cs
public class GenericProperty{ public string type {get; set;} ; public string[] values { get; set;} }
请问有没有更优的方式定义接收类,不用显式列出所有属性名称?
解决方案
可以用Dictionary<string, GenericProperty>替代自定义的MyTestObject类,动态接收任意名称的属性,无需提前定义。
修改后的POST接口
直接将参数类型改为字典:
[HttpPost] public void testAPI(Dictionary<string, GenericProperty> filterModel){ // 处理逻辑,比如遍历所有过滤条件 foreach(var kvp in filterModel){ string propertyName = kvp.Key; GenericProperty filterValue = kvp.Value; // 针对每个属性的过滤规则做处理 } }
原理说明
- .NET的JSON序列化器(如System.Text.Json或Newtonsoft.Json)会自动将JSON中的键值对映射到
Dictionary<string, T>结构中 - 这里的
T为GenericProperty,完全匹配JSON中每个属性的值结构 - 无论ag-grid返回多少个不确定名称的属性,都能被完整接收,无需修改代码
额外优化(可选)
如果需要更面向对象的封装,可让MyTestObject继承自Dictionary<string, GenericProperty>:
public class MyTestObject : Dictionary<string, GenericProperty> { // 可添加自定义方法,比如筛选特定类型的过滤条件 public IEnumerable<GenericProperty> GetStringFilters() { return this.Values.Where(v => v.type == "string"); } }
接口参数依然使用MyTestObject,既保留动态接收能力,又能扩展自定义逻辑。
内容的提问来源于stack exchange,提问作者just-an-average-programmer
相关产品推荐
相关产品推荐

