I have an Optional
struct that defines an implicit conversion from the original type:
public readonly struct Optional<T>
{
// Some code removed to make the example simpler: original code: https://github.com/dotnet/roslyn/blob/main/src/Compilers/Core/Portable/Optional.cs
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
}
}
This means that e.g. this will work:
Optional<long> field = 5;
Now I want to deserialize json to a class that contains this struct:
public class Foo
{
Optional<long> Bar {get; set;}
}
------
{
"Bar": 5
}
Right now deserializing this json causes this exception:
System.Text.Json.JsonException The JSON value could not be converted to Optional`1[System.Int64].
Is there a way to make this work?
P.S. This actually works out of the box in Newtonsoft.Json:
var a = JsonSerializer.Deserialize<Foo>("{\"Bar\":45}"); // This fails
var b = JsonConvert.DeserializeObject<Foo>("{\"Bar\":45}"); // This works