Specifying a JSON enum string converter for a list property #99777
-
I have a property which is an enumeration of enums (in my case it is a using System.Text.Json;
using System.Text.Json.Serialization;
using NUnit.Framework;
const string json = """
{
"values": ["One", "Two", "Three"]
}
""";
HasNumbers? hasNumbers = JsonSerializer.Deserialize<HasNumbers>(json, NumberSerializerContext.Default.HasNumbers);
Assert.That(hasNumbers, Is.Not.Null);
Number[]? numbers = hasNumbers.Values;
Assert.That(numbers, Is.Not.Null);
Assert.That(numbers, Has.Length.EqualTo(3));
Assert.Multiple(() =>
{
Assert.That(numbers[0], Is.EqualTo(Number.One));
Assert.That(numbers[1], Is.EqualTo(Number.Two));
Assert.That(numbers[2], Is.EqualTo(Number.Three));
});
[JsonSourceGenerationOptions(
// UseStringEnumConverter = true // this approach does not work
)]
[JsonSerializable(typeof(HasNumbers))]
public sealed partial class NumberSerializerContext : JsonSerializerContext;
public class HasNumbers
{
// [JsonConverter(typeof(JsonStringEnumConverter<Number>))] // this does not work either
public Number[]? Values { get; set; }
}
public enum Number
{
One,
Two,
Three,
} Is there any way to do what I am doing? Preferably in an AOT-friendly way. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Setting Note that [JsonSourceGenerationOptions(
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true
)]
[JsonSerializable(typeof(HasNumbers))]
public sealed partial class NumberSerializerContext : JsonSerializerContext; |
Beta Was this translation helpful? Give feedback.
Depends on whether you want the desired behavior specifically only on the
Values
property, or specifically on theNumbers
enum type regardless where it is being used in the object graph being (de)serialized.If the behavior should be specific to the
Values
property (with other properties of the same enum type being unaffected), currently you would need to write a custom JsonConverter that then executes the StringEnumConverter on the collection items, similar to this implementation: #54189 (comment). This converter would then be applied to theValues
property using the[JsonConverter]
attribute. The…