Created
June 9, 2024 14:07
-
-
Save tomaszprasolek/930f600f9d414045c0088c6c2d718fe7 to your computer and use it in GitHub Desktop.
Use custom JsonConverter to serialize and deserialize values
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
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
string json = """ | |
{ | |
"Status": "PENDING" | |
} | |
"""; | |
var customerTask = JsonSerializer.Deserialize<CustomerTask>(json); | |
Console.WriteLine($"Status: {customerTask!.Status}"); | |
internal sealed class CustomerTask | |
{ | |
[JsonConverter(typeof(CustomerTaskStatusJsonConverter))] | |
public CustomerTaskStatus Status { get; set; } | |
} | |
internal enum CustomerTaskStatus | |
{ | |
Pending = 1, | |
Completed = 2, | |
Cancelled = 3 | |
} | |
internal sealed class CustomerTaskStatusJsonConverter : JsonConverter<CustomerTaskStatus> | |
{ | |
/// <inheritdoc /> | |
public override CustomerTaskStatus Read(ref Utf8JsonReader reader, | |
Type typeToConvert, | |
JsonSerializerOptions options) | |
{ | |
return Enum.Parse<CustomerTaskStatus>(reader.GetString()!, true); | |
} | |
/// <inheritdoc /> | |
public override void Write(Utf8JsonWriter writer, | |
CustomerTaskStatus value, | |
JsonSerializerOptions options) | |
{ | |
writer.WriteStringValue(value.ToString().ToUpper()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment