-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add the installation and usage instructions.
- Loading branch information
1 parent
b6ccced
commit 3842f87
Showing
1 changed file
with
68 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,68 @@ | ||
# StrEnum.System.Text.Json | ||
# StrEnum.System.Text.Json | ||
|
||
Allows for [StrEnum](https://github.com/StrEnum/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-6.\*. | ||
|
||
## Installation | ||
|
||
You can install [StrEnum.System.Text.Json](https://www.nuget.org/packages/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: | ||
|
||
```csharp | ||
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` : | ||
|
||
```csharp | ||
var options = new JsonSerializerOptions().UseStringEnums(); | ||
``` | ||
|
||
### Serialize to JSON: | ||
|
||
```csharp | ||
var ctct = new Race { Name = "Cape Town Cycle Tour", Sport = Sport.RoadCycling }; | ||
|
||
var json = JsonSerializer.Serialize(ctct, options); | ||
``` | ||
|
||
The above produces: | ||
|
||
```json | ||
{"Name":"Cape Town Cycle Tour","Sport":"ROAD_CYCLING"} | ||
``` | ||
|
||
### Deserialize from JSON: | ||
|
||
```csharp | ||
var race = JsonSerializer.Deserialize<Race>(json, options); | ||
``` | ||
|
||
`race` is equivalent to: | ||
|
||
```csharp | ||
new { Name = "Cape Town Cycle Tour", Sport = Sport.RoadCycling }; | ||
``` | ||
|
||
## License | ||
|
||
Copyright © 2022 [Dmitry Khmara](https://dmitrykhmara.com). | ||
|
||
StrEnum is licensed under the [MIT license](LICENSE.txt). |