Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PublishTrimmed error with System.Text.Json

I am trying to publish my c# code with the argument -p:PublishTrimmed=true. It uses System.Text.Json, and gives me a warning. /home/USER/tymaker-config-builder/Program.cs(69,33): warning IL2026: Using member 'System.Text.Json.JsonSerializer.Serialize<SerializeExtra.LetterInfo>(SerializeExtra.LetterInfo, 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. [/home/USER/tymaker-config-builder/tymaker-config-builder.csproj].

It also gives me another very similar warning: /home/tymaker-config-builder/Program.cs(69,13): Trim analysis warning IL2026: SerializeExtra.Program.Main(): Using member 'System.Text.Json.JsonSerializer.Serialize<TValue>(TValue,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. [/home/USER/tymaker-config-builder/tymaker-config-builder.csproj]

Is there a way to resolve this issue while keeping my output trimmed? I do not want to have to publish ~70MB executables on my GitHub.

Here is my code:

using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;


namespace SerializeExtra
{
    
    public class LetterInfo
    {
        public string? gift { get; set; }
        public string? party { get; set; }
        public string? sender { get; set; }
        public string? address { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            
            Console.Write("Thank-you note bot JSON generator");
            Console.Write('\n');
            Console.Write("Version 1.0.0");
            Console.Write("\n\n");
            var letterInfo = new LetterInfo { };
            Console.Write("What gift are you getting?\nThis gift will be used until changed.\nIf you want to skip this, type \"skip\"\n\n");
            letterInfo.gift = Console.ReadLine();
            if (letterInfo.gift == "skip")
            {
                letterInfo.gift = null;
            }
            Console.Write("\n\n");
            Console.Write("What party are the thank-you notes for?\nThis party will be used until changed.\nIf you want to skip this, type \"skip\"\n\n");
            letterInfo.party = Console.ReadLine();
            if (letterInfo.party == "skip")
            {
                letterInfo.party = null;
            }
            Console.Write("\n\n");
            Console.Write("What is your name?\nThis sender will be used until changed.\nIf you want to skip this, type \"skip\"\n\n");
            letterInfo.sender = Console.ReadLine();
            if (letterInfo.sender == "skip")
            {
                letterInfo.sender = null;
            }
            Console.Write("\n\n");
            if (letterInfo.sender == null)
            {
                Console.Write("What do you want your closing word(s) to be? (e.g: {answer}, Joe)\nThis closing word will be used until changed.\nIf you want to skip this, type \"skip\"\n\n");
            } else
            {
                Console.Write("What do you want your closing word(s) to be? (e.g: {answer}, " + letterInfo.sender + ")\nThis closing word will be used until changed.\nIf you want to skip this, type \"skip\"\n\n");
            }
            letterInfo.address = Console.ReadLine();
            if (letterInfo.address == "skip")
            {
                letterInfo.address = null;
            }
            Console.Write("\n\n");
            
            var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(letterInfo, options);

            string savePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            File.WriteAllText(Path.Combine(savePath, "tymaker.json"), jsonString);
            Console.Write("Configuration file (tymaker.json) is saved at " + savePath + "\n\n");
        }
    }
}
like image 590
Anti-Apple4life Avatar asked May 28 '26 21:05

Anti-Apple4life


1 Answers

This Microsoft article explains how to use source generation when working with System.Text.Json, which is required when trimming is enabled.

For your example, you would create a "context" class, derived from JsonSerializerContext.

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(LetterInfo))]
internal partial class LetterInfoContext : JsonSerializerContext
{
}

And when you call JsonSerializer.Serialize or JsonSerializer.Deserialize, you need to pass in the context:

string jsonString = JsonSerializer.Serialize(
    letterInfo,
    LetterInfoContext.Default.LetterInfo);

Now, if you try to publish, you should see that it's successful without giving these warnings:

❯ dotnet publish -c release -r linux-x64 --sc ./SerializeExtra.csproj
MSBuild version 17.8.3+195e7f5a3 for .NET
  Determining projects to restore...
  All projects are up-to-date for restore.
  SerializeExtra -> /home/user/repos/temp/SerializeExtra/bin/release/net8.0/linux-x64/SerializeExtra.dll
  SerializeExtra -> /home/user/repos/temp/SerializeExtra/bin/release/net8.0/linux-x64/publish/
like image 170
devklick Avatar answered May 30 '26 10:05

devklick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!