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)

Metadata

Metadata

Labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions