2

Using Newtonsoft Json.Net (11.0.2) with the StringEnumConverter seems to work most of the time but sometimes we get a Json array with numbers in it that do not correspond to the array. Does anyone know how this may be happening?

I have tried setting up tests to simulate the strange output but it works as expected every time. I am thinking that maybe there is a memory issue that causes strange behavior since we only see this occasionally in production.

So we configure our serializer settings with StringEnumConverter and use the following enum as an example:

    public enum TestType
    {
        FirstOption,
        SecondOption,
        ThirdOption
    }

var example = new List<TestType>() { TestType.FirstOption, TestType.SecondOption };

That is an example of the expected output

[
"FistOption",
"SecondOption"
]

This is the output we get most of the time, however, in production we get

[13]

The enum does not have 13 items in it so how does it generate 13? Is there some binary encoding?

Brandon
  • 61
  • 8
  • Probably, my crystal ball says that the real enum type has the [Flags] attribute. [Look here](https://stackoverflow.com/q/43143175/17034). – Hans Passant Jun 05 '19 at 16:17
  • Try setting `StringEnumConverter.AllowIntegerValues = false` as shown in [StringEnumConverter invalid int values](https://stackoverflow.com/q/35479669/3744182). – dbc Jun 06 '19 at 00:45
  • @HansPassant we do not explicitly set [Flags] however I will look into that to see if we can decode what the 13 means – Brandon Jun 06 '19 at 11:55
  • @dbc unfortunately we can no longer set that option to false because the data in our production system will not deserialize if we do that – Brandon Jun 06 '19 at 11:56

1 Answers1

0

Enums in .NET aren't checked so there's nothing that prevents you from populating it with arbitrary ordinal value. The issue isn't in JSON.NET, but somewhere where you populate the data to be serialized.

Here's a simple test case:

[JsonConverter(typeof(StringEnumConverter))]
public enum TestType
{
    FirstOption,
    SecondOption,
    ThirdOption
}

public const TestType Unlucky13 = (TestType)13;

public static void Main()
{
    var testCase = new[] { TestType.FirstOption, TestType.SecondOption };
    Console.WriteLine(JsonConvert.SerializeObject(testCase));
    testCase[0] = Unlucky13;
    Console.WriteLine(JsonConvert.SerializeObject(testCase));
}

The output is:

["FirstOption","SecondOption"]
[13,"SecondOption"]
Peter Wolf
  • 3,700
  • 1
  • 15
  • 30
  • Thanks for linking that article. I have now added some validation to try and prevent this from happening again. Although we still cannot find the source of this strange behavior. We never do any setting via type cast – Brandon Jun 06 '19 at 14:32