ASP.NET 核心 JSON 模型绑定 int 到枚举
ASP.NET core JSON model binding int to enum
场景
我想将具有整数值的传入 JSON 请求映射到相应的枚举值。
下面的代码针对问题进行了简化,实际上 MyRequest class.
上有更多字段
数据码
public enum Policy
{
Unknown = 0,
Policy1 = 1,
Anticipated = 2
}
public enum Design
{
Unknown = 0,
Project = 1,
Days = 2
}
public class Policies
{
public Policy? PolicyId { get; set; }
public Design? DesignId { get; set; }
}
class MyRequest
{
public int Id { get; set; }
public Policies Policies { get; set; }
}
JSON请求
{
"policies": {
"policyId": 2,
"designId": 2
},
"id": 1
}
控制器代码
[HttpPut]
public async Task<IActionResult> Put(MyRequest request)
{
// reques.Policies.DesignId is null
// reques.Policies.PolicyId is null
}
在更深入地研究这个问题并且几乎 没有微软文档 之后,我发现 this 类似的问题给了我正确的方向:实施自定义 JSONConverter
.
JSON转换器
public class ContractConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Policies) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var rawValue = serializer.Deserialize<dynamic>(reader);
var policyId = (Policy)(rawValue.policyId);
var designId = (Design)(rawValue.designId);
return new Policies(policyId, designId);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite => false;
}
Startup.cs
services.AddControllers()
.AddNewtonsoftJson(o=> o.SerializerSettings.Converters.Add(new ContractConverter()));
场景
我想将具有整数值的传入 JSON 请求映射到相应的枚举值。 下面的代码针对问题进行了简化,实际上 MyRequest class.
上有更多字段数据码
public enum Policy
{
Unknown = 0,
Policy1 = 1,
Anticipated = 2
}
public enum Design
{
Unknown = 0,
Project = 1,
Days = 2
}
public class Policies
{
public Policy? PolicyId { get; set; }
public Design? DesignId { get; set; }
}
class MyRequest
{
public int Id { get; set; }
public Policies Policies { get; set; }
}
JSON请求
{
"policies": {
"policyId": 2,
"designId": 2
},
"id": 1
}
控制器代码
[HttpPut]
public async Task<IActionResult> Put(MyRequest request)
{
// reques.Policies.DesignId is null
// reques.Policies.PolicyId is null
}
在更深入地研究这个问题并且几乎 没有微软文档 之后,我发现 this 类似的问题给了我正确的方向:实施自定义 JSONConverter
.
JSON转换器
public class ContractConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Policies) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var rawValue = serializer.Deserialize<dynamic>(reader);
var policyId = (Policy)(rawValue.policyId);
var designId = (Design)(rawValue.designId);
return new Policies(policyId, designId);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite => false;
}
Startup.cs
services.AddControllers()
.AddNewtonsoftJson(o=> o.SerializerSettings.Converters.Add(new ContractConverter()));