Skip to content
An extended version from the JsonStringEnumConverter which supports attributes like EnumMember, Display and Description
C#
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples/ConsoleApp
src/System.Text.Json.EnumExtensions
.gitignore
CHANGELOG.md
Directory.Build.props
GitHubReleaseNotes.txt
LICENSE
README.md
System.Text.Json.EnumExtensions Solution.sln
System.Text.Json.EnumExtensions Solution.sln.DotSettings
azure-pipelines.yml

README.md

System.Text.Json.Extensions

Some extensions to the JsonStringEnumConverter which supports attributes like EnumMember, Display and Description

Info

  Build Azure Build Status
  NuGet NuGet: EnumExtensions.System.Text.Json
  MyGet (preview) MyGet: EnumExtensions.System.Text.Json

Installing

You can install from NuGet using the following command in the package manager window:

Install-Package EnumExtensions.System.Text.Json

Or via the Visual Studio NuGet package manager.

If you use the dotnet command:

dotnet add package EnumExtensions.System.Text.Json

Usage Example - EnumMember

Define Enum and add attributes

Define an Enum and annotate the Enum fields with the EnumMemberAttribute:

enum WeatherType
{
    [EnumMember(Value = "Zonnig")]
    Sunny,

    [EnumMember(Value = "Helder")]
    Clear
}

Add Converter

Add the new JsonStringEnumConverterWithAttributeSupport to the Converters via the JsonSerializerOptions:

var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport());

Serialize an object

var weatherForecast = new WeatherForecast
{
    WeatherType = WeatherType.Sunny
};

var weatherForecastSerialized = JsonSerializer.Serialize(weatherForecast, options);
Console.WriteLine(weatherForecastSerialized); // {"WeatherType":"Zonnig"}

Deserialize an object

Deserialize works by using the same options:

var json = "{\"WeatherType\":\"Zonnig\"}";
var weatherForecastDeserialized = JsonSerializer.Deserialize<WeatherForecast>(json, options);

Usage Example - Display and Description

It's also possible to annotate Enum fields with these attributes:

Define Enum and add attributes

enum WeatherType
{
    [EnumMember(Value = "Zonnig")]
    Sunny,

    [Display(Name = "Helder")]
    Clear,

    [Description("Bewolkt")]
    Cloudy
}

Add Converter

! 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.

You can’t perform that action at this time.