Skip to content

StrEnum/StrEnum.System.Text.Json

Repository files navigation

StrEnum.System.Text.Json

Allows for StrEnum string enum JSON serialization and deserialization with System.Text.Json.

The package targets .NET Standard 2.0 and can be used with System.Text.Json 4.6.0-7.*.

Installation

You can install StrEnum.System.Text.Json using the .NET CLI:

dotnet add package StrEnum.System.Text.Json

Usage

Create a string enum and a class that contains it:

public class Sport : StringEnum<Sport>
{
    public static readonly Sport RoadCycling = Define("ROAD_CYCLING");
}

public class Race
{
    public string Name { get; set; }
    public Sport Sport { get; set; }
}

Configure JsonSerializerOptions by calling the UseStringEnums() method and pass it to JsonSerializer :

var options = new JsonSerializerOptions().UseStringEnums();

Serialize to JSON:

var ctct = new Race { Name = "Cape Town Cycle Tour", Sport = Sport.RoadCycling };

var json = JsonSerializer.Serialize(ctct, options);

The above produces:

{"Name":"Cape Town Cycle Tour","Sport":"ROAD_CYCLING"}

Deserialize from JSON:

{"Name":"Cape Town Cycle Tour","Sport":"ROAD_CYCLING"}

The above JSON can be deserialized into a C# object that contains a StrEnum enum:

var race = JsonSerializer.Deserialize<Race>(json, options);

// race is equivalent to:
new { Name = "Cape Town Cycle Tour", Sport = Sport.RoadCycling };

License

Copyright © 2022 Dmitry Khmara.

StrEnum is licensed under the MIT license.