主要问题是枚举是否可以有“.”在名字中间,我的例子如下:
所以有人给我发送了这个 openapi yaml 文件,如下所示,我正在用 C# 生成一个控制器。 这是我收到的 yaml:
/actions/MyAction:
post:
summary: blahblah
tags:
- action
parameters:
- in: body
name: MyAction
required: true
schema:
type: object
properties:
data:
type: object
properties:
target:
type: string
location:
description: thelocation
type: string
enum:
- location.Outdoor1
- location.Outdoor2
- location.Outdoor3
在c#中为:
生成的对象类 public partial class Data2
{
[Newtonsoft.Json.JsonProperty("target", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public stringTarget { get; set; }
[Newtonsoft.Json.JsonProperty("location", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
public Data2Location? Location { get; set; }
}
对于枚举我有:
public enum Data2Location
{
[System.Runtime.Serialization.EnumMember(Value = @"location.Outdoor1")]
location_Outdoor1= 0,
[System.Runtime.Serialization.EnumMember(Value = @"location.Outdoor2")]
location_Outdoor2 = 1,
[System.Runtime.Serialization.EnumMember(Value = @"location.Outdoor3")]
location_Outdoor3= 2,
}
控制器
[Microsoft.AspNetCore.Mvc.HttpPost, Microsoft.AspNetCore.Mvc.Route("actions/MyAction")]
public Microsoft.AspNetCore.Mvc.IActionResult MyAction([Microsoft.AspNetCore.Mvc.FromBody] Data2data)
{
return _implementation.MyAction(data);
}
我的麻烦在于枚举“thelocation”,因为当我从 Postman 发送请求时,所有对象 在上述请求的方法中为空: 发布到 http://localhost:5000/api/v1/actions/Myaction 与身体:
{
"data": {
"target": "thetarget"
"location":"location.Outdoor2"
}
}
答案 0 :(得分:1)
因此,由于我没有得到任何帮助,我决定进行调查并找到了解决方法...
我认为问题在于 newtonsoft 没有正确解析可为空的枚举。所以我做了一个新的 stringenumconverter,它在读取 JSON 时考虑到了这一点,因为他们的代码是开源的,我可以做到:
public class NullableStringEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
catch
{
if (IsNullableType(objectType))
return null;
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
}
private static bool IsNullableType(Type t)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
有了这个,当在枚举中找不到它时,我的位置被设置为“空”,如果它在属性 EnumMember 中找到一个等于给定它工作的字符串,而对象的其余部分则被很好地解析。