-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JSON source gen does not work correctly with nullable structs with custom converter #70475
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsRepro: using System.Text.Json;
using System.Text.Json.Serialization;
namespace Repro
{
internal class Program
{
static void Main(string[] args)
{
// prints: {"Bar":"B"}
Console.WriteLine(JsonSerializer.Serialize<FooStruct>(new FooStruct { Bar = Foo.B }));
// error, see below for more details
Console.WriteLine(JsonSerializer.Serialize<FooStruct>(new FooStruct { Bar = Foo.B }, EnumContext.Default.FooStruct));
}
}
[JsonSerializable(typeof(FooStruct))]
internal partial class EnumContext : JsonSerializerContext
{
}
internal struct FooStruct
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public Foo? Bar { get; set; }
}
internal enum Foo
{
A,
B
}
} Exception message:
|
Another similar case: using System.Text.Json;
using System.Text.Json.Serialization;
namespace Repro
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine(JsonSerializer.Serialize<FooStruct>(new FooStruct { Bar = Foo.B }, EnumContext.Default.FooStruct));
}
}
[JsonSerializable(typeof(FooStruct))]
internal partial class EnumContext : JsonSerializerContext
{
}
internal struct FooStruct
{
[JsonConverter(typeof(FooConverter))]
public Foo? Bar { get; set; }
}
internal class FooConverter : JsonConverter<Foo>
{
public override Foo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return (Foo)reader.GetInt32();
}
public override void Write(Utf8JsonWriter writer, Foo value, JsonSerializerOptions options)
{
writer.WriteNumberValue((int)value);
}
}
internal enum Foo
{
A,
B
}
} fails to compile:
|
this seems like an existing bug without external reports (found only while doing unrelated code changes which touched this) and also a bit too risky to do at this point in release so moving to Future |
@krwq ran across this today. Any suggested workarounds while we wait for a fix? Other than not using the source generator... |
Fixed in #84208 |
Repro:
Exception message:
The text was updated successfully, but these errors were encountered: