Runtime: Serialization/deserialization with camel case option not working for enum type

Created on 16 May 2019  路  8Comments  路  Source: dotnet/runtime

Sample test:

public enum CamelCaseEnum
{
    This,
    Is,
    CamelCase
}
[Fact]
public static void Serialize_CamelCaseFromAttribute()
{
    string json = JsonSerializer.ToString(CamelCaseEnum.CamelCase, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    Assert.Equal(@"""camelCase""", json);
}

[Fact]
public static void Deserialize_CamelCaseFromAttribute()
{
    CamelCaseEnum e = JsonSerializer.Parse<CamelCaseEnum>(@"""camelCase""", new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    Assert.Equal(CamelCaseEnum.CamelCase, e);
}

[Fact]
public static void NamedEnumCommaCaseInsensitiveTest()
{
    EnumContainer<NamedEnumWithComma> c2 = JsonSerializer.Parse<EnumContainer<NamedEnumWithComma>>(@"{""Enum"":"",THIRD""}");
    Assert.Equal(NamedEnumWithComma.Third, c2.Enum);
}
public enum NamedEnumWithComma
{
    [EnumMember(Value = "@first")]
    First,

    [EnumMember(Value = "@second")]
    Second,

    [EnumMember(Value = ",third")]
    Third,

    [EnumMember(Value = ",")]
    JustComma
}
[Fact]
public static void CamelCaseTextFlagEnumDeserialization()
{
    string json = @"{
  ""Enum"": ""first, second""
}";
    EnumContainer<FlagsTestEnum> c = JsonSerializer.Parse<EnumContainer<FlagsTestEnum>>(json, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    Assert.Equal(FlagsTestEnum.First | FlagsTestEnum.Second, c.Enum);
}
area-System.Text.Json json-functionality-doc

All 8 comments

cc @JeremyKuhne as this points to some interesting test cases for the "treat enum as string" feature.

PropertyNamingPolicy only applies to property names and not enum value names. We may want to add a custom option for enum value names as well, in the future.

As test cases not supported am ok with closing this issue, but not sure if we want to keep this issue for adding custom option

@JeremyKuhne can you PTAL as part of your Enum work

The PropertyNamingPolicy is not intended for enum value names.

During the review of adding PropertyNamingPolicy we also added DictionaryKeyPolicy and discussed adding an "EnumValuePolicy" but didn't think it was necessary for 3.0.

Recommend moving to Future.

The JsonStringEnumConverter supports naming policy that only changes casing. Arbitrary mapping we won't support for 3.0.

I've created a project which allows using attributes like EnumMember, Display and Description.

Project: https://github.com/StefH/System.Text.Json.EnumExtensions
NuGet: https://www.nuget.org/packages/EnumExtensions.System.Text.Json

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bencz picture bencz  路  3Comments

jzabroski picture jzabroski  路  3Comments

Timovzl picture Timovzl  路  3Comments

v0l picture v0l  路  3Comments

btecu picture btecu  路  3Comments