-
-
Notifications
You must be signed in to change notification settings - Fork 535
Inheritance
NJsonSchema supports inheritance for JSON Schema and C#/TypeScript code generation. For inheritance to work, the serialized JSON object must contain a discriminator field which identifies the actual subclass. To support this, your base class needs to add this field during serialization and select the correct type during deserialization. Also, the generated schema must specify this discriminator field so that the correct deserialization logic can be generated. In your source C# base classes where the schema is generated from and which are used for serialization, you need to add the JsonInheritanceConverter
and KnownTypeAttribute
s:
public class Container
{
public Animal Animal { get; set; }
}
[JsonConverter(typeof(JsonInheritanceConverter), "discriminator")]
[KnownType(typeof(Dog))]
public class Animal
{
public string Foo { get; set; }
}
public class Dog : Animal
{
public string Bar { get; set; }
}
An instance of Container
is then serialized to the following JSON:
{
"Animal": {
"discriminator": "Dog",
"Bar": "bar",
"Foo": "foo"
}
}
And the generated JSON Schema for the Container
looks like:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"x-typeName": "Container",
"additionalProperties": false,
"properties": {
"Animal": {
"oneOf": [
{
"$ref": "#/definitions/Animal"
},
{
"type": "null"
}
]
}
},
"definitions": {
"Dog": {
"type": "object",
"x-typeName": "Dog",
"additionalProperties": false,
"properties": {
"Bar": {
"type": [
"null",
"string"
]
}
},
"allOf": [
{
"$ref": "#/definitions/Animal"
}
]
},
"Animal": {
"type": "object",
"x-typeName": "Animal",
"discriminator": "discriminator",
"additionalProperties": false,
"required": [
"discriminator"
],
"properties": {
"Foo": {
"type": [
"null",
"string"
]
},
"discriminator": {
"type": "string"
}
}
}
}
}
From this JSON Schema you can now generate C# or TypeScript code which correctly processes the discriminator field (using the same converter in the generated C# class and a special fromJS
method in TypeScript:
TODO