ASP.NET MVC Core API将枚举序列化为字符串 [英] ASP.NET MVC Core API Serialize Enums to String
问题描述
如何在ASP.NET MVC Core 3.0中将Enum字段序列化为String而不是Int?我不能用旧的方式做.
How to serialize Enum fields to String instead of an Int in ASP.NET MVC Core 3.0? I'm not able to do it the old way.
services.AddMvc().AddJsonOptions(opts =>
{
opts.JsonSerializerOptions.Converters.Add(new StringEnumConverter());
})
我遇到错误:
无法从"Newtonsoft.Json.Converters.StringEnumConverter"进行转换到"System.Text.Json.Serialization.JsonConverter"
cannot convert from 'Newtonsoft.Json.Converters.StringEnumConverter' to 'System.Text.Json.Serialization.JsonConverter'
推荐答案
新的System.Text.Json序列化
ASP.NET MVC Core 3.0使用内置的JSON序列化.使用 System.Text.Json.Serialization.JsonStringEnumConverter
(带有"Json"前缀):
New System.Text.Json serialization
ASP.NET MVC Core 3.0 uses built-in JSON serialization. Use System.Text.Json.Serialization.JsonStringEnumConverter
(with "Json" prefix):
services
.AddMvc()
// Or .AddControllers(...)
.AddJsonOptions(opts =>
{
opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
})
您还可以使用传统"Newtonsoft.Json序列化:
You can also use "traditional" Newtonsoft.Json serialization:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
然后:
services
.AddControllers()
.AddNewtonsoftJson(opts => opts.Converters.Add(new StringEnumConverter()));
这篇关于ASP.NET MVC Core API将枚举序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!