我已经梳理了MS 文档,但找不到与NewtonSoft JsonPropertyRequired等效的属性。
我要找的是这个:
public class Videogame
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我是否只是遗漏了某些东西,或者 Microsoft 库中不存在这种级别的验证?
我将json属性反序列化为枚举,但是当属性为空字符串时,我遇到了处理案例的问题.
将值""转换为"EnrollmentState"类型时出错
我正在尝试反序列化该state属性requiredItem.
{
"currentStage" : "Pre-Approved",
"stages" : ["Applicant", "Pre-Approved", "Approved", "Enrolled"],
"requiredItems" : [{
"id" : 1,
"name" : "Documents",
"state" : ""
}, {
"id" : 2,
"name" : "Eligibility Verification",
"state" : "complete"
}, {
"id" : 3,
"name" : "Placement Information",
"state" : "incomplete"
}
]
}
Run Code Online (Sandbox Code Playgroud)
RequiredItem 上课和枚举......
public class RequiredItem {
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public string id { get; …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用视图模型和枚举在 ASP.NET Core Web API 项目中实现 HttpPost 方法[FromBody]。过去,将视图模型与[FromBody]属性绑定效果很好。
在我的特定场景中,我想提供一个 JSON 端点,在其中将给定值转换为具有不同名称的 C# 枚举。这个例子应该解释我想要实现的目标:
公共枚举 WeatherEnum
{
[EnumMember(值 = "好")]
好的,
[EnumMember(值 = "坏")]
坏的
}
在内部,我想使用WeatherEnum.Goodand WeatherEnum.Bad,并且我的端点的使用者希望使用小写值。因此,我尝试将 JSON 正文中传递的值映射到我的 Enum 表示形式。
我读过有关EnumMember属性 和 的内容StringEnumConverter。我已经从新的 ASP.NET Core Web API 3.0 模板创建了一个最小示例(您需要添加这些 NuGet 包Microsoft.Extensions.DependencyInjection、Microsoft.AspNetCore.Mvc.NewtonsoftJson和Newtonsoft.Json)
配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(json =>
{
json.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
services.AddControllers(); …Run Code Online (Sandbox Code Playgroud)