Skip to content

Instantly share code, notes, and snippets.

@tomaszprasolek
Created June 9, 2024 14:07
Show Gist options
  • Save tomaszprasolek/930f600f9d414045c0088c6c2d718fe7 to your computer and use it in GitHub Desktop.
Save tomaszprasolek/930f600f9d414045c0088c6c2d718fe7 to your computer and use it in GitHub Desktop.
Use custom JsonConverter to serialize and deserialize values
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