Discriminators serve as marker fields for object deserialization in our SDKs. Consider that you have a field type or an endpoint return type set to a specific model type, say
Building. If the
Building model has two child models,
Office, it should technically be allowed for the server to return JSON response corresponding to the
Building type itself or to any of its child classes i.e.
Office. Essentially, a
School or an
Office is a
Building as well.
APIMatic's SDKs which support discriminator fields use the values of these fields to determine which class object to deserialize the server response into.
Take for example the JSON below:
If the type of this response is set to be the
Building model, the discriminator is set to be "buildingType" and its value i.e. "school" matches the discriminator value of the School model, the SDK will deserialize this JSON into an instance of the
School class. In typed languages, the newly created instance of the School class will be type-casted to the
Lets walk you through a quick example of discriminators usage.
Create a new model and set a discriminator and a corresponding discriminator value for it.
Create a few child models of the model from the previous step and set their discriminator values for the discriminator set in the parent class.
Set the type of a field or the return type of an endpoint to the base model created in the first step.
That's it! The SDK will deserialize the server's response into the appropriate type based on the value of the discriminator field in the response.