JSON contract modifiers cannot be used with source generation #121304
Replies: 2 comments 8 replies
-
|
The overwriting behavior of |
Beta Was this translation helpful? Give feedback.
-
|
I am in a similar situation: an using System.Text.Json;
using System.Text.Json.Serialization;
namespace NativeAotDev;
public class Config
{
public string Version { get; set; } = "中文";
}
public partial class Program
{
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)]
[JsonSerializable(typeof(Config))]
public partial class ConfigJsonContext : JsonSerializerContext { }
static void Main(string[] args)
{
var config = new Config();
var json = JsonSerializer.Serialize(config, ConfigJsonContext.Default.Config);
// json = Regex.Unescape(json);
Console.WriteLine(json);
}
}Of course I can use public partial class ConfigJsonContext
{
private readonly static global::System.Text.Json.JsonSerializerOptions s_defaultOptions = new()
{
PropertyNamingPolicy = global::System.Text.Json.JsonNamingPolicy.CamelCase,
WriteIndented = true,
};
...Edit: as @eiriktsarpalis said above, now I found the solution: private static JsonSerializerOptions Options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All),
TypeInfoResolver = AppBarJsonContext.Default
};
...
var json = JsonSerializer.Serialize(config, Options.GetTypeInfo(typeof(Config))); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Description
It does not appear to be possible to customise JSON contracts with modifiers at the same time as using
System.Text.Jsonsource generation. A workaround is available but is extremely limited, functioning only in the most trivial of cases.Reproduction Steps
Execute
ReproCase.SerialiseWithModifiersfrom the code below. It should throw an exception, but it does not because the modifier is not executed.Expected behavior
It must be possible to add modifiers to a source-generated
JsonContextat the same time as configuring other options. I would expect the code given above to achieve this.It is not enough to add modifiers to the source generated context class. It must be possible to define them per operation at runtime.
Actual behavior
The constructor of
JsonSerializerContextforcibly overwritesJsonSerializerOptions.TypeInfoResolverwith itself. All appended modifiers are lost.Regression?
No response
Known Workarounds
A workaround has been suggested on StackOverflow. Unfortunately this solution only works on the top-level
JsonTypeInfoobject, and child objects still don't see the modifier. I've not been able to find the offending line but it seems likely thatJsonTypeInfo.OriginatingResolveris involved, because this points to the "raw" source-generated resolver.Configuration
.Net 9
Other information
No response
Beta Was this translation helpful? Give feedback.
All reactions