.NET Core 3.0 StringEnumConverter 未序列化为字符串

And*_*doe 12 c# serialization json json.net

使用以下方法装饰您的枚举时:

[JsonConverter(typeof(StringEnumConverter))]
public EventEntity Entity { get; set; }
Run Code Online (Sandbox Code Playgroud)

并将其序列化 JsonConvert.SerializeObject(myEvent)

您可能会注意到枚举没有序列化为字符串,而是作为默认整数。

Ngo*_*uoc 19

如果您使用的是普通的System.Text.Jsonwithout Newtonsoft.JSON,则此代码段Startup.cs可能会有所帮助:

// using System.Text.Json.Serialization
services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });
Run Code Online (Sandbox Code Playgroud)

这里的关键是在System.Text.Json(注意类名与 from 中的不同Newtonsoft.JSON)中定义的这个转换器:JsonStringEnumConverter


And*_*doe 18

真的很简单,但让我挠了 20 分钟左右...

使用 JsonConverter 属性时,第一个智能感知导入是: using System.Text.Json.Serialization

但你应该使用: using Newtonsoft.Json;

  • 请注意,试图回答这个问题的人永远不会猜到这一点,这就是为什么在您的问题中提供最小的、**可重复的**代码示例非常重要。 (3认同)

小智 17

确保添加的Microsoft.AspNetCore.Mvc.NewtonsoftJsonNuGet包,并呼吁.AddNewtonsoft()在启动ConfigureServices(IServiceCollection services)之后方法正确services.AddMvc(...)。如果你不这样做,一切都可以正常编译,似乎可以运行,但实际上,什么都不能正常工作。

更多细节在这里