0

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
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • 1
    I get a compilation error for your "struct" code: 'Program.Optional' does not contain a constructor that takes 1 arguments – D A Mar 15 '22 at 14:20
  • I just made it "simpler" to avoid too many lines, I'll add a reference to a full class – Ilya Chernomordik Mar 15 '22 at 14:23
  • 1
    There's no support for that built in to System.Text.Json AFAIK. You'll need to use the [`JsonConverter` factory pattern](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#sample-factory-pattern-converter) as shown in [Custom JSON serializer for optional property with System.Text.Json](https://stackoverflow.com/q/63418549/3744182). (The question has the required factory for `Optional`.) In fact, does that question answer yours? – dbc Mar 15 '22 at 14:34
  • 1
    @dbc Thanks, I have actually found that I already use JsonConverter to serialize Optional probably from that answer :) Adding the same `JsonConverter` to the settings for deserialization just made it work! – Ilya Chernomordik Mar 15 '22 at 14:52

0 Answers0