Skip to content

Latest commit

 

History

History
69 lines (45 loc) · 1.49 KB

File metadata and controls

69 lines (45 loc) · 1.49 KB

StrEnum.System.Text.Json

Lets you serialize and deserialize StrEnum string enums to JSON via System.Text.Json.

Targets .NET Standard 2.0; works with System.Text.Json 4.6.0 – 10.x.

Installation

Install StrEnum.System.Text.Json via the .NET CLI:

dotnet add package StrEnum.System.Text.Json

Usage

Defining a string enum and a model

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; }
}

Configuring the serializer

Call UseStringEnums() on a JsonSerializerOptions instance and pass it to JsonSerializer:

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

Serializing to JSON

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

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

Produces:

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

Deserializing from JSON

The same JSON can be deserialized back to a Race:

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

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

License

Copyright © 2025 Dmytro Khmara.

StrEnum is licensed under the MIT license.