Skip to content

Validation of polymorphic properties #1878

@schoetbi

Description

@schoetbi

I have the following class hierarchy

public class TypeWithAbstractMembers
{
    [JsonDerivedType(typeof(DerivedClassA), "A")]
    [JsonDerivedType(typeof(DerivedClassB), "B")]
    [JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")]
    public class AbstractClass
    {
        public int BaseProp { get; set; }
    }

    public class DerivedClassA : AbstractClass
    {
        public int AProp { get; set; }
    }

    public class DerivedClassB : AbstractClass
    {
        public int BProp { get; set; }
    }

    public AbstractClass AbstractProperty { get; set; }
}

Schema created by NJsonSchema

I created the schema with this

var settings = new SystemTextJsonSchemaGeneratorSettings()
{
    SchemaType = SchemaType.JsonSchema, 
    AllowReferencesWithProperties = true
};
var schema = JsonSchemaGenerator.FromType<TypeWithAbstractMembers>(settings);
var jsonSchema = schema.ToJson();

The resulting schema is this polymorphicSchema.json

It uses the discriminator mapping

"discriminator": {
        "propertyName": "Type",
        "mapping": {
          "A": "#/definitions/DerivedClassA",
          "B": "#/definitions/DerivedClassB"
        }
      },

But with this schema the following json does not validate on jsonschemavalidator because there are no additional properties allowed for the base type

{
    "AbstractProperty": {
        "Type": "B",
        "BaseProp": 1,
        "BProp": 10
    }
}

Removal of additionalProperties

I tried to remove the line 28 with "additionalProperties". Here the fixed schema file that validates polymorphicSchemaFixed.json
But then the problem is, that all additional properties are also "valid"

OneOf Validation

Maybe the best way to implement this is with "oneOf"
polymorphicSchemaOneOf.json

This would require to copy all properties from the base class to all derived classes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions