首页 > 解决方案 > .NET Core 3.0 StringEnumConverter 未序列化为字符串

问题描述

装饰枚举时:

[JsonConverter(typeof(StringEnumConverter))]
public EventEntity Entity { get; set; }

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

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

标签: c#jsonserializationjson.net

解决方案


如果您使用的是System.Text.Json没有的纯文本Newtonsoft.JSON,则此代码段Startup.cs可能会有所帮助:

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

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


推荐阅读