SHARE THIS ARTICLE

Discriminators

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, School and 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. School or Office. Esentially, 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:

{
  "buildingType": "school",
  "classrooms": 10
}

If the type of this response is set to be the Building model, the discrimininator 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 typecasted to the Building type.

Usage Example

Lets walk you through a quick example of discriminators usage.

  1. The first step is to create a new model and set a discriminator and a corresponding discriminator value for it. New Model

  2. Next, 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. Child Model Child Model

  3. Finally, set the type of a field or the return type of an endpoint to the base model created in the first step. Endpoint Return Type

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.


Have questions? Submit a request.