I'm trying to figure out how to use JsonSerializer.Deserialize<T> when application code trimming enabled. The compiler suggests I need to use an overload that takes a JsonTypeInfo or JsonSerializerContext. I searched the web for solutions, but could not find any. I found some relevant examples, but they appear to be too complicated for such a simple task and it lead me to believe I'm missing something important here.
The compiler says I need to make sure all of the required types are preserved to prevent breaking functionality in production. How can I do this?
project.csproj
...
<PropertyGroup>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>link</TrimMode>
</PropertyGroup>
Code
using System.Text.Json;
public class Program
{
public static void Main()
{
Thing thing = Parse<Thing>("{}");
}
public static T Parse<T>(string json)
{
T test = JsonSerializer.Deserialize<T>(json);
return test;
}
}
public struct Thing
{
public int Key1 { get; init; }
}
Error
Using member 'System.Text.Json.JsonSerializer.Deserialize(string, System.Type, System.Text.Json.JsonSerializerOptions?)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.
I'm not sure if it's the right way to do it, but the warning is gone.
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
public class Program
{
public static void Main()
{
JsonTypeInfo<Thing> typeInfo = SourceGenerationContext.Default.Thing
Thing thing = Parse<Thing>("{}", typeInfo);
}
public static T Parse<T>(string json, JsonTypeInfo<T> typeInfo)
{
T test = JsonSerializer.Deserialize<T>(json, typeInfo);
return test;
}
}
public struct Thing
{
public int Key1 { get; set; } = 0;
}
[JsonSerializable(typeof(Thing))]
internal partial class SourceGenerationContext : JsonSerializerContext { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With