Swashbuckle.AspNetCore icon indicating copy to clipboard operation
Swashbuckle.AspNetCore copied to clipboard

[Bug]: All enum values show up as "null" when using JSON Source Generation

Open lschloetterer opened this issue 1 month ago • 3 comments

Describe the bug

When using this setting in the .csproj file:

<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>

All enum values are null

Expected behavior

Enum values are serialized to integers by default (or strings when using the JSON string enum converter)

Actual behavior

All enum values are null: UI: "Available values : null, null, null"

swagger.json:

 "components": {
        "schemas": {
            "TimeRange": {
                "enum": [
                    null,
                    null,
                    null
                ],
                "type": "integer",
                "format": "int32"
            }
        }
    }

Steps to reproduce

  1. Disable reflection based serialization in .csproj:
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
  1. create JSON context:
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(TimeRange))]
[JsonSerializable(typeof(IEnumerable<WeatherForecast>))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
  1. Register context in Program.cs:
builder.Services.AddControllers()
  .AddJsonOptions(o => o.JsonSerializerOptions.TypeInfoResolverChain.Add(SourceGenerationContext.Default));
  1. Add Controller with enum URL Parameter:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{

  [HttpGet("by-range/{range}")]
  public IEnumerable<WeatherForecast> Get(TimeRange range)
  {

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
      TemperatureC = Random.Shared.Next(-20, 55)
    })
    .ToArray();
  }
}
public class WeatherForecast
{
  public int TemperatureC { get; set; }
}
public enum TimeRange
{
  DAILY,
  WEEKLY,
  MONTHLY
}

Exception(s) (if any)

No response

Swashbuckle.AspNetCore version

7.2.0

.NET Version

8.0.401

Anything else?

No response

lschloetterer avatar Jan 10 '25 09:01 lschloetterer