Skip to content

[JsonSchemaExporter]: Respecting data annotations + schema version #117043

@marekott

Description

@marekott

Background and motivation

When trying to migrate from Newtonsoft.Json.Schema to pure JsonSchemaExporter (without any third party libraries) I have noticed that at least two features are missing.

  1. Respecting data annotations (for example including in schema min and max of given type)
  2. Possibility to select schema draft version

Would you guys consider adding them so the transition would be possible without taking dependency on external libraries?

Newtonsoft.Json.Schema:

{
  "$schema" : "http://json-schema.org/draft-07/schema#",
  "definitions" : {
    "Nested<UInt16>" : {
      "type" : "object",
      "properties" : {
        "required" : {
          "type" : "integer",
          "minimum" : 0.0,
          "maximum" : 65535.0
        },
        "nullable" : {
          "type" : [ "integer", "null" ],
          "minimum" : 0.0,
          "maximum" : 65535.0
        }
      },
      "required" : [ "required" ]
    }
  },
  "type" : "object",
  "properties" : {
    "required" : {
      "type" : "integer",
      "minimum" : 0.0,
      "maximum" : 65535.0
    },
    "nullable" : {
      "type" : [ "integer", "null" ],
      "minimum" : 0.0,
      "maximum" : 65535.0
    },
    "nested" : {
      "$ref" : "#/definitions/Nested<UInt16>"
    }
  },
  "required" : [ "required", "nested" ]
}

STJ:

{
  "type" : [ "object", "null" ],
  "properties" : {
    "required" : {
      "type" : "integer"
    },
    "nullable" : {
      "type" : [ "integer", "null" ]
    },
    "nested" : {
      "type" : "object",
      "properties" : {
        "required" : {
          "type" : "integer"
        },
        "nullable" : {
          "type" : [ "integer", "null" ]
        }
      },
      "required" : [ "required", "nullable" ]
    }
  },
  "required" : [ "required", "nullable", "nested" ]
}

API Proposal

JsonSerializerOptions options = new(JsonSerializerOptions.Default)
{
    RespectDataAnnotations= true,
    Version = "draft-07"
};

API Usage

JsonSerializerOptions options = new(JsonSerializerOptions.Default)
{
    PropertyNamingPolicy = JsonNamingPolicy.KebabCaseUpper,
    NumberHandling = JsonNumberHandling.WriteAsString,
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
    RespectDataAnnotations= true,
    Version = "draft-07"
};

JsonNode schema = options.GetJsonSchemaAsNode(typeof(MyPoco));
Console.WriteLine(schema.ToString());

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions