dotnet / dotnet/aspnetcore

When Serialize using source generation the JsonOptions of the Source generator are ignored

Open
#53,417 0 comments 0 reactions 0 assignees View on GitHub
area-minimal
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

In .net 8 when configuring Json the JsonSerializer options of the attribute JsonSourceGenerationOptions are being ignored.

I cannot change the default SerializerOptions to the one that is being generated, because the property JsonSerializerOptions is get only.

A very simple scenario could be seen in this image:

![image](https://github.com/dotnet/aspnetcore/assets/6615999/5e19a4fc-253d-4bce-bb3c-d5f51364214c)

Also is good to mention that I put a breakpoint on the Analyzer System.Text.Json, in the handler logic ( that seems OK). But the breakpoint does never get hit.

If the field DefaultSerializerOptions was a protected one the application could extend the class JsonOptions to insert the JsonSerializerOptions that the application needs. Another way could be to select every option on the JsonSerializerOptions to be the one that MyContext has

### Expected Behavior

I expect the lastName not to be serialized

### Steps To Reproduce

using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

builder.Services.ConfigureHttpJsonOptions(opt => opt.SerializerOptions.TypeInfoResolverChain.Insert(0, MyContext.Default));

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapGet("/{name}", (string name) => $"Hello {name}");

app.MapGet("/Customer/{name}", (string name, string? lastName) => new Customer(name, lastName));

app.Run();

internal record Customer(string Name, string? LastName);

[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Customer))]
internal partial class MyContext : JsonSerializerContext
{

}

### Exceptions (if any)

_No response_

### .NET Version

8.0.101

### Anything else?

VS 17.8.4

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.