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
There problem is most likely here: https://github.com/dotnet/corefx/blob/2c75f5a09f770f3118e09abc35bdf88c1c7120b0/src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterEnum.cs#L37
I'm working on a PR to fix this.
Most helpful comment
Fixed in https://github.com/dotnet/corefx/pull/37508.