JamesNK / Newtonsoft.Json.Schema

Json.NET Schema is a powerful, complete and easy to use JSON Schema framework for .NET
http://www.newtonsoft.com/jsonschema
Other
248 stars 107 forks source link

Schema generation - When using a custom JSchemaGenerationProvider some DataAnnotations are ignored #277

Open Epicycle23 opened 3 years ago

Epicycle23 commented 3 years ago

When using a custom JSchemaGenerationProvider DataAnnotations like MinLength/MaxLength are not generated in the schema.

public class ExampleSchemaProvider : JSchemaGenerationProvider
{
    public override JSchema GetSchema(JSchemaTypeGenerationContext context){
        JSchema schema = context.Generator.Generate(context.ObjectType);
        // ...
        return schema;
   }
}

When this generation provider is present data annotations like MinLength,MaxLength stop working although Required still works as expected.

public class Example{
    [MinLength(1)]
    [Required]
    public string SomeString { get; set; }
}

without ExampleSchemaProvider

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "examplewithoutprovider",
  "title": "Example",
  "type": "object",
  "properties": {
    "SomeString": {
      "type": "string",
      "minLength": 1
    }
  },
  "required": [
    "SomeString"
  ]
}

with ExampleSchemaProvider

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "examplewithprovider",
  "title": "Example",
  "type": "object",
  "properties": {
    "SomeString": {
      "type": "string"
    }
  },
  "required": [
    "SomeString"
  ]
}
K-Pavlov commented 1 year ago

I hit the same problem.

~After a bit of debugging I found out that the problem seems to come from JSchemaGeneratorProxy not receiving the MemberProperty from the JSchemaTypeGenerationContext . When there are generation providers (see JSchemaGeneratorInternal.cs ) a JSchemaTypeGenerationContext is created and when we use the context.Generator in our custom JSchemaGenerationProvider, the JSchemaGeneratorProxy is used leading to the loss of the MemberProperty => no attribute information => the described problem occurs.~

~Adding the MemberProperty to the JSchemaGeneratorProxy and using it in JSchemaGeneratorProxy.Generate fixes the issues. Everything seems alright and all tests pass.~

Actually I don't think the above makes sense, but using the generator like this context.Generator.Generate(context.ObjectType, context.Required, context.MemberProperty); fixes the issue :)