【发布时间】:2020-01-31 06:11:43
【问题描述】:
使用枚举:
namespace AppGlobals
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BoardSymbols
{
[EnumMember(Value = "X")]
First = 'X',
[EnumMember(Value = "O")]
Second = 'O',
[EnumMember(Value = "?")]
EMPTY = '?'
}
}
我想为我的 api 定义一个模型:
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
namespace Assignment_1
{
public class MyRequest
{
//...
[Required]
[MinLength(9)]
[MaxLength(9)]
[JsonProperty("changeTypes", ItemConverterType = typeof(JsonStringEnumConverter))]
public AppGlobals.BoardSymbols[] GameBoard { get; set; }
}
}
其中GameBoard 应序列化为 JSON 作为字符串数组,其名称由EnumMember 属性指定。此方法改编自Deserialize json character as enumeration。但是,它不起作用。如果我将枚举更改为:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BoardSymbols
{
X='X',
Y='Y'
}
但我显然达到了“空”枚举的限制。我该怎么做?
更新 2:
我的创业公司没有 AddNewtonsoftJson(),完全转换为 Newtonsoft。现在我的错误可能更具可操作性:
System.InvalidCastException: Unable to cast object of type 'CustomJsonStringEnumConverter' to type 'Newtonsoft.Json.JsonConverter'.
at Newtonsoft.Json.Serialization.JsonTypeReflector.CreateJsonConverterInstance(Type converterType, Object[] args)
这是有道理的,给我的解决方案here 指定了一个 JsonConverterFactory .. 我只需要原始 JsonConverter 来代替我的用例。
【问题讨论】:
-
你没有使用json.net你正在使用system.text.json。 System.Text.Json 不支持
[EnumMember()]重命名枚举值,你必须编写自己的自定义转换器。要做到这一点,请参阅System.Text.Json: How do I specify a custom name for an enum value?。或者,您可以切换回 Json.NET,如 Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0? 所示。这可能是其中一个或两个的副本,具体取决于您首选的序列化程序。 -
您打算使用 Json.NET 还是 System.Text.Json?
JsonStringEnumConverter是 System.Text.Json 的一部分。 Newtonsoft 使用StringEnumConverter。 -
实际上,我认为切换回 Json.Net 的链接太旧了.. 我的 Newtsonsoft 导入正在工作,但是像
services.AddControllers() .AddNewtonsoftJson();这样我收到一个错误,表明 AddNewtonsoftJson 不是会员IMVCBuilder。这是一个值得写出来的问题,以回应一个真正的答案,你能提供一个吗? -
@dbc 重新提出您的第二个建议。谢谢。我尝试使用 Newtonsoft.Json.Converters 和 StringEnumConverter .. 遗憾的是,这仍然失败
-
我根据我的建议使用
CustomJsonStringEnumConverter,编辑了中间更新,从而简化了您的问题。该转换器在这里不起作用。我更新了对System.Text.Json: How do I specify a custom name for an enum value? 的回答,表明我的CustomJsonStringEnumConverter仅适用于序列化,并为反序列化提供一些替代建议。如果不合适,请随时恢复我的编辑。
标签: c# asp.net json.net asp.net-core-webapi asp.net-core-3.1