dotnet / dotnet/aspnetcore

JsonSerializerContext still doesnt work out of the box

Open
#51,397 5 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

`shared/WeatherForecast`:
```
public partial record WeatherForecast
{
public DateOnly Date { get; init; }
public int TemperatureC { get; init; }
public string? Summary { get; init; }
[JsonIgnore]
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

[JsonSerializable(typeof(WeatherForecast[]))]
public partial class WeatherForecastSerializer : JsonSerializerContext { }
}
```
server:
```
services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Add(WeatherForecast.WeatherForecastSerializer.Default));
...
app.MapGet("/api/WeatherForecast", (WeatherService weatherService, int listSize) => weatherService.UpdateForecasts(listSize));
```
client:
```
internal class WeatherService(HttpClient http)
{
public async Task UpdateForecasts(int listSize) => await http.GetFromJsonAsync($"api/WeatherForecast?listSize={listSize}", WeatherForecast.WeatherForecastSerializer.Default.WeatherForecastArray) ?? throw new();
}
```

This still produces `WeatherForecast` with all values 0/empty.

### Expected Behavior

I dont have to add `[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]` to every single `JsonSerializerContext` to make it actually work.

Or at the very least a compile time error or a runtime error...

### Steps To Reproduce

See above

### Exceptions (if any)

Nope, it compiles just fine, it runs just fine... IT JUST DOESN'T WORK!

### .NET Version

8.0.100-rc.2.23502.2

### Anything else?

_No response_

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.