Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET Core 3.0 StringEnumConverter未序列化为字符串_C#_Json_Serialization_Json.net - Fatal编程技术网

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

C# .NET Core 3.0 StringEnumConverter未序列化为字符串,c#,json,serialization,json.net,C#,Json,Serialization,Json.net,使用以下内容装饰枚举时: [JsonConverter(typeof(StringEnumConverter))] public EventEntity Entity { get; set; } 并用 JsonConvert.SerializeObject(myEvent) 您可能会注意到,枚举不是作为字符串序列化的,而是作为默认整数序列化的。简单的枚举确实让我挠头了20分钟左右 使用JsonConverter atribute时,第一个intellisense导入是: 使用System.Te

使用以下内容装饰枚举时:

[JsonConverter(typeof(StringEnumConverter))]
public EventEntity Entity { get; set; }
并用
JsonConvert.SerializeObject(myEvent)


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

简单的枚举确实让我挠头了20分钟左右

使用JsonConverter atribute时,第一个intellisense导入是:
使用System.Text.Json.Serialization

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

您必须安装Newtonsoft.Json库,在NuGet软件包管理器中找到最新版本,并将其添加到项目中

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

确保添加
Microsoft.AspNetCore.Mvc.NewtonsoftJson
NuGet包,并在启动
ConfigureServices(IServiceCollection services)
方法中调用
services.AddMvc(…)
。如果不这样做,一切都可以编译,似乎可以运行,但事实上,任何东西都不能正常工作


更多详细信息

如果您使用的是纯
System.Text.Json
而不使用
Newtonsoft.Json
,则
Startup.cs
中的此代码段可能有助于:

//使用System.Text.Json.Serialization
services.AddControllers()
.AddJsonOptions(选项=>
{
options.JsonSerializerOptions.converts.Add(新的jsonStringUnumConverter());
});

这里的关键内容是
System.Text.Json
中定义的this转换器(注意类名不同于
Newtonsoft.Json
):

System.Text.Json
中,可以使用
jsonstringumconverter
替换
Newtonsoft.Json.converter.StringEnumConverter

services.AddMvc().AddJsonOptions(options =>
{
   options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});


注意,试图回答这个问题的人永远不会猜到这一点,这就是为什么在你的问题中提供一个最小的、可复制的代码样本是非常重要的。这也是我遇到的问题。谢谢是的,我也面临这个问题。感谢您的回答。以上所有答案都是正确的,对于ASP.NET Core 3.0及以上版本,这就是银弹!谢谢@delepster。