Runtime: System.Text.Json fails to parse enums with negative values

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

This is a regression from Newtonsoft that causes existing ASP.NET Core applications to fail when upgrading to .NET Core 3.0.

Reproduction:

using System;
using System.Text.Json.Serialization;

namespace Sandbox
{
    public enum ReactionType
    {
        Neutral = 0,
        Like = 1,
        Dislike = -1,
    }

    public class Reaction
    {
        public ReactionType Value { get; set; }

        public Reaction() { }

        public Reaction(ReactionType value) => Value = value;
    }

    public class Program
    {
        public static void Main()
        {
            var values = new Reaction[]
            {
                new Reaction(ReactionType.Neutral),
                new Reaction(ReactionType.Like),
                new Reaction(ReactionType.Dislike),
            };

            foreach (var value in values)
            {
                var json = JsonSerializer.ToString(value);
                Console.WriteLine(json);

                try
                {
                    var obj = JsonSerializer.Parse<Reaction>(json);
                    Console.WriteLine(obj.Value);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            Console.ReadKey(true);
        }
    }
}

Output:

{"Value":0}
Neutral
{"Value":1}
Like
{"Value":-1}
System.Text.Json.JsonReaderException: The JSON value from [Sandbox.Reaction].Value could not be converted to Sandbox.ReactionType.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException_DeserializeUnableToConvertValue(Type propertyType, Utf8JsonReader& reader, ReadStack& state)
   at System.Text.Json.Serialization.JsonPropertyInfoNotNullable`3.Read(JsonTokenType tokenType, JsonSerializerOptions options, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.JsonSerializer.HandleValue(JsonTokenType tokenType, JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& state)
   at System.Text.Json.Serialization.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& state)
   at System.Text.Json.Serialization.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.JsonSerializer.ParseCore(String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonSerializer.Parse[TValue](String json, JsonSerializerOptions options)
   at Sandbox.Program.Main() in C:\Users\paul\source\repos\Sandbox\Sandbox\Program.cs:line 40
area-System.Text.Json bug tenet-compatibility

Most helpful comment

All 2 comments

Was this page helpful?
0 / 5 - 0 ratings