0

I'm trying to call the JsonSerializer.Deserialize override that takes a Utf8JsonReader and JsonSerializerOptions. I'm doing this because it's most convenient for my JsonConverter<T> implementation. To my surprise, even though I'm targeting a runtime that has the method (.NET 6), my compiler doesn't see the method. I do see that it exists, but the method has a [RequiresUnreferencedCode] attribute on it.

Is there a way for me to make that method available? I see this relates to some feature called "trimming" which I'm not familiar with, but I don't know why my project thinks it needs to do trimming. As I understand it, this might have something to do with reflection; is there a way for me to tell the compiler I don't care and don't try to do this trimming weirdness? If it matters, this is for a library that is published as a nuget package.

I've tried putting [RequiresUnreferencedCode] on my own method, but that doesn't work; the compiler still isn't resolving the JsonSerializer.Deserialize method overload.

I can't exactly make this "reproducable" without a bunch of setup, but here's the code I explained above for illustration:

internal class MyJsonConverter : JsonConverter<ISomeInterface>
{
    public override void Write(
        Utf8JsonWriter writer,
        ISomeInterface value,
        JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(
            writer,
            value.ToSerializableConfig(),
            options);
    }

    public override ISomeInterface? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        // This is the line where the compiler isn't finding the method
        var deserializedObj = JsonSerializer.Deserialize<SerializableClass>(
            reader,
            options);
        
        ISomeInterface? converted = null;

        var successfulConversion =
            ConcreteTypeA.TryFromSerializable(deserializedObj, out converted)
            || ConcreteTypeB.TryFromSerializable(deserializedObj, out converted)
            || ConcreteTypeC.TryFromSerializable(deserializedObj, out converted);

        return converted;
    }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Jacob
  • 77,566
  • 24
  • 149
  • 228

1 Answers1

2

You are missing the ref keyword in your call, the mentioned method JsonSerializer.Deserialize<TValue>(Utf8JsonReader, JsonSerializerOptions) has first parameter (Utf8JsonReader) marked with ref keyword:

var deserializedObj = JsonSerializer.Deserialize<SerializableClass>(
    ref reader,
    options);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132