Home > Enterprise >  Receiving double quotes after serialization
Receiving double quotes after serialization

Time:06-29

I'm using Macross.Json.Extensions and there is a method which accepts Interval interval. When I serialize it, I expect to get it as 15, not \"15\". In this case, the serialization puts double quotes and basically the output of asd is \"15\", instead of juts 15. How do I fix it?

public void Test(Interval interval)
{
    var asd = JsonSerializer.Serialize(interval, new JsonSerializerOptions
    {
        NumberHandling = JsonNumberHandling.AllowReadingFromString
    }); // Equals to: \"15\". Expected: 15
    var intervalMinutes = int.Parse(interval.ToString());
}
[JsonConverter(typeof(JsonStringEnumMemberConverter))]
public enum Interval
{
    [EnumMember(Value = "1")]
    OneMinute,

    [EnumMember(Value = "5")]
    FiveMinute,

    [EnumMember(Value = "15")]
    FifteenMinute,

    [EnumMember(Value = "30")]
    ThirtyMinute,

    [EnumMember(Value = "60")]
    OneHour,

    [EnumMember(Value = "240")]
    FourHour,

    [EnumMember(Value = "1440")]
    OneDay,

    [EnumMember(Value = "10080")]
    OneWeek,

    [EnumMember(Value = "21600")]
    FifteenDays
}

CodePudding user response:

EnumMemberAttribute exits to serialise enumerable values as their symbolic – identifier – names, rather than the actual numeric value used at runtime.

In this case the value passed to the attribute is a minute count, rather than using that as the value of the enum's values (which is odd: serialising a value that could change by the introduction of another value, eg. TwentyMinutes).

This would be far better not using EnumMemberAttribute and setting each member directly:

[JsonConverter(typeof(JsonStringEnumMemberConverter))]
public enum Interval
{
    OneMinute = 1,
    FiveMinute = 5,
    FifteenMinute = 15,
    ThirtyMinute = 30,
    OneHour = 60,
    FourHour = 240,
    OneDay = 1440,
    OneWeek = 10080,
    FifteenDays = 21600
}
  • Related