Skip to content

Unexpected nullability for get-only properties for json schema produced by STJ #131602

Description

@Youssef1313

Description

When a property doesn't have a setter, its info will have IsSetNullable set to true, and then the JsonSchemaExporter will make the schema nullable.

Reproduction Steps

#nullable enable

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Schema;

Console.WriteLine(JsonSchemaExporter.GetJsonSchemaAsNode(JsonSerializerOptions.Default, typeof(C)));

class C
{
    public IEnumerable<string> Values => [];
    public string SingleValueGetOnly { get; }
    public string SingleValueGetSet { get; set; }
}

Expected behavior

The Values and SingleValueGetOnly properties shouldn't be marked nullable.

Actual behavior

{
  "type": [
    "object",
    "null"
  ],
  "properties": {
    "Values": {
      "type": [
        "array",
        "null"
      ],
      "items": {
        "type": [
          "string",
          "null"
        ]
      }
    },
    "SingleValueGetOnly": {
      "type": [
        "string",
        "null"
      ]
    },
    "SingleValueGetSet": {
      "type": "string"
    }
  }
}

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

I think the summary of where the behavior comes from is:

https://github.com/dotnet/dotnet/blob/df95cfb2142d47c72046c09dc049162e588342ed/src/runtime/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Helpers.cs#L897-L898

if (propertyInfo is not null)
{
return propertyInfo.IsGetNullable || propertyInfo.IsSetNullable;
}

A property without a setter will have its info with IsSetNullable = true (the nullability info is reported as "unknown" - but IsSetNullable will consider unknown as if it's nullable)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions