Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 14 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# StrEnum.System.Text.Json

Allows for [StrEnum](https://github.com/StrEnum/StrEnum/) string enum JSON serialization and deserialization with System.Text.Json.
Lets you serialize and deserialize [StrEnum](https://github.com/StrEnum/StrEnum/) string enums to JSON via System.Text.Json.

The package targets .NET Standard 2.0 and can be used with System.Text.Json 4.6.0-10.\*.
Targets .NET Standard 2.0; works with System.Text.Json 4.6.010.x.

## Installation

You can install [StrEnum.System.Text.Json](https://www.nuget.org/packages/StrEnum.System.Text.Json/) using the .NET CLI:
Install [StrEnum.System.Text.Json](https://www.nuget.org/packages/StrEnum.System.Text.Json/) via the .NET CLI:

```
dotnet add package StrEnum.System.Text.Json
```

## Usage

Create a string enum and a class that contains it:
### Defining a string enum and a model

```csharp
public class Sport : StringEnum<Sport>
Expand All @@ -29,33 +29,31 @@ public class Race
}
```

Configure `JsonSerializerOptions` by calling the `UseStringEnums()` method and pass it to `JsonSerializer` :
### Configuring the serializer

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

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

### Serialize to JSON:
### Serializing to JSON

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

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

The above produces:
Produces:

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

### Deserialize from JSON:

```json
{"Name":"Cape Town Cycle Tour","Sport":"ROAD_CYCLING"}
```
### Deserializing from JSON

The above JSON can be deserialized into a C# object that contains a StrEnum enum:
The same JSON can be deserialized back to a `Race`:

```csharp
var race = JsonSerializer.Deserialize<Race>(json, options);
Expand All @@ -68,4 +66,4 @@ new { Name = "Cape Town Cycle Tour", Sport = Sport.RoadCycling };

Copyright &copy; 2025 [Dmytro Khmara](https://dmytrokhmara.com).

StrEnum is licensed under the [MIT license](LICENSE.txt).
StrEnum is licensed under the [MIT license](LICENSE.txt).
Loading