Extensions to the JsonStringEnumConverter which supports attributes like EnumMember, Display and Description.
$ dotnet add package EnumExtensions.System.Text.JsonSome extensions to the JsonStringEnumConverter which supports attributes like EnumMember, Display and Description
Define an Enum and annotate the Enum fields with the EnumMemberAttribute:
enum WeatherType
{
[EnumMember(Value = "Zonnig")]
Sunny,
[EnumMember(Value = "Helder")]
Clear
}
Add the new JsonStringEnumConverterWithAttributeSupport to the Converters via the JsonSerializerOptions:
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport());
var weatherForecast = new WeatherForecast
{
WeatherType = WeatherType.Sunny
};
var weatherForecastSerialized = JsonSerializer.Serialize(weatherForecast, options);
Console.WriteLine(weatherForecastSerialized); // {"WeatherType":"Zonnig"}
Deserialize works by using the same options:
var json = "{\"WeatherType\":\"Zonnig\"}";
var weatherForecastDeserialized = JsonSerializer.Deserialize<WeatherForecast>(json, options);
It's also possible to annotate the Enum with a [JsonConverter] so that you don't need to manually registerd the JsonStringEnumConverterWithAttributeSupport to the Converters via the JsonSerializerOptions.
Define an Enum
[JsonConverter(typeof(JsonStringEnumConverterWithAttributeSupport))] to the Enum[JsonConverter(typeof(JsonStringEnumConverterWithAttributeSupport))]
enum WeatherType
{
[EnumMember(Value = "Zonnig")]
Sunny,
[EnumMember(Value = "Helder")]
Clear
}
Generic Attribute is also supported:
[JsonConverter(typeof(JsonStringEnumConverterWithAttributeSupport<WeatherType>))]
enum WeatherType
{
[EnumMember(Value = "Zonnig")]
Sunny,
[EnumMember(Value = "Helder")]
Clear
}
This works the same as using Option 1.
Note that only Enum values which are annotated with EnumMember are supported.
It's also possible to annotate Enum fields with these attributes:
enum WeatherType
{
[EnumMember(Value = "Zonnig")]
Sunny,
[Display(Name = "Helder")]
Clear,
[Description("Bewolkt")]
Cloudy
}
! By default, the Display and Description are disabled, use the following line to enable these.
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null, true, true, true, true));
Serializing and Deserializing works the same.
Entity Framework Extensions and Dapper Plus are major sponsors and proud to contribute to the development of System.Text.Json.Extensions.