Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
manidos Avatar asked Oct 26 '25 08:10

manidos


1 Answers

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 { }
like image 166
manidos Avatar answered Oct 28 '25 22:10

manidos