Skip to content

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

@lschloetterer

Description

@lschloetterer

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bughelp-wantedA change up for grabs for contributions from the communityversion-minorA change suitable for release in a minor version

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions