Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save r-pankevicius/95e6ae7cbe9ee9b1884be50d55a75b15 to your computer and use it in GitHub Desktop.
Save r-pankevicius/95e6ae7cbe9ee9b1884be50d55a75b15 to your computer and use it in GitHub Desktop.
System.Text.Json.Serialization.JsonStringEnumConverter allows case insensitive enum values by default in .net 5.0
using System;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace TestCaseInsensitiveJsonStringEnum
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Season
{
Spring,
Summer,
Autumn,
Winter
}
public class YearSeason
{
public int Year { get; set; }
public Season Season { get; set; }
}
internal static class Program
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
static void Main(string[] args)
{
TestProperCaseEnumValue();
TestInproperCaseEnumValue();
TestInvalidEnumValue();
}
private static void TestProperCaseEnumValue()
{
const string json = @"
{
""year"": 2022,
""season"": ""Summer""
}
";
var yearsSeasons = JsonSerializer.Deserialize<YearSeason>(json, JsonSerializerOptions);
Debug.Assert(yearsSeasons is not null);
Debug.Assert(yearsSeasons.Year == 2022);
Debug.Assert(yearsSeasons.Season == Season.Summer);
}
private static void TestInproperCaseEnumValue()
{
const string json = @"
{
""year"": 2022,
""season"": ""summER""
}
";
var yearsSeasons = JsonSerializer.Deserialize<YearSeason>(json, JsonSerializerOptions);
Debug.Assert(yearsSeasons is not null);
Debug.Assert(yearsSeasons.Year == 2022);
Debug.Assert(yearsSeasons.Season == Season.Summer);
}
private static void TestInvalidEnumValue()
{
const string json = @"
{
""year"": 2022,
""season"": ""INVALID_VALUE""
}
";
try
{
JsonSerializer.Deserialize<YearSeason>(json, JsonSerializerOptions);
}
catch (JsonException)
{
return; // all fine, what's expected
}
throw new Exception($"FAIL: Invalid {nameof(Season)} value was silently swallowed.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment