'How to use JsonSerializer.Deserialize<T> with application code trimming enabled?
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.
- Are there any simple solutions to this problem?
- Should I ignore this warning?
- In what cases this code might break functionality?
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.
Solution 1:[1]
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 { }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | manidos |
