Created
April 5, 2022 18:37
-
-
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
This file contains hidden or 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; | |
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