Using the enum:
namespace AppGlobals
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BoardSymbols
{
[EnumMember(Value = "X")]
First = 'X',
[EnumMember(Value = "O")]
Second = 'O',
[EnumMember(Value = "?")]
EMPTY = '?'
}
}
I would like to define a model for my 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; }
}
}
Where GameBoard should serialize to JSON as an array of strings with names specified by the EnumMember attributes. This approach is adapted from Deserialize json character as enumeration. However, it does not work. This does works if I change the enum to:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BoardSymbols
{
X='X',
Y='Y'
}
But I obviously hit a limit on the 'empty' enumeration. How can I do this?
update 2:
I did not have AddNewtonsoftJson() in my startup, converting over fully to Newtonsoft. Now my error is perhaps more actionable:
System.InvalidCastException: Unable to cast object of type 'CustomJsonStringEnumConverter' to type 'Newtonsoft.Json.JsonConverter'.
at Newtonsoft.Json.Serialization.JsonTypeReflector.CreateJsonConverterInstance(Type converterType, Object[] args)
This makes sense, the solution prescribed to me here specified a JsonConverterFactory .. I just need the raw JsonConverter for my use case instead.
[EnumMember()]renaming of enum values, you have to write your own custom converter. To do it see System.Text.Json: How do I specify a custom name for an enum value?. Or, you could switch back to Json.NET as shown in Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?. This could be a duplicate of either or both depending upon your preferred serializer.JsonStringEnumConverteris part of System.Text.Json. Newtonsoft usesStringEnumConverter.services.AddControllers() .AddNewtonsoftJson();I get an error that AddNewtonsoftJson is not a member of IMVCBuilder. This is the sort of problem that deserves being written about in rsponse to a real answer, could you provide one?CustomJsonStringEnumConverter. That converter isn't going to work here; I updated my answer to System.Text.Json: How do I specify a custom name for an enum value? to indicate that myCustomJsonStringEnumConverteronly works for serialization, and to provide some alternative suggestions for deserialization. Feel free to revert my edit if it wasn't appropriate.