简体   繁体   中英

Inheritance and discriminator in base class

I have class operation:

public class Operation
{
    public string Type { get; set; }

    public OperationOptions Options { get; set; }
}

Where value of Type defines type of Options . But I have to add discriminator to OperationOptions type

[KnownType(typeof(EchoOptions))]
[KnownType(typeof(VetDocumentAcceptanceOptions))]
[JsonConverter(typeof(JsonInheritanceConverter), "discriminator")]
public class OperationOptions
{
}

public class EchoOptions : OperationOptions
{
}

public class VetDocumentAcceptanceOptions : OperationOptions
{
}

So I get in swagger.json:

  "OperationOptions": {
    "type": "object",
    "discriminator": {
      "propertyName": "discriminator",
      "mapping": {
        "EchoOptions": "#/components/schemas/EchoOptions",
        "VetDocumentAcceptanceOptions": "#/components/schemas/VetDocumentAcceptanceOptions"
      }
    }

But I don't have property Discriminator in OperationOptions in my model.

Is there any way to use Type in Operation as discriminator for OperationOptions ?

The JsonInheritanceConverter will automatically add the discriminator property to the serialized JSON and use this property when deserializing JSON to a type to select the correct type. It's better to actually not see the property as a C# property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM