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;
}
}