jsonschema2pojo icon indicating copy to clipboard operation
jsonschema2pojo copied to clipboard

Discriminator value and inheritance

Open trajano opened this issue 11 months ago • 0 comments

This is a specific use case but posing it as a discussion (I do recommend we have Discussion enabled on the project to clarify ideas)

Assuming we this schema

{
  "$schema" : "https://json-schema.org/draft/2020-12/schema",
  "title" : "Question",
  "type" : "object",
  "oneOf" : [ {
    "$ref" : "./MultipleChoiceQuestion.schema.json"
  }, {
    "$ref" : "./SimpleAnswerQuestion.schema.json"
  } ],
  "additionalProperties": false,
  "javaTypeDiscriminatorProperty": "type"
}

{
  "$schema" : "https://json-schema.org/draft/2020-12/schema",
  "title" : "QuestionBase",
  "type" : "object",
  "requiredProperties": [ "type", "id" ],
  "additionalProperties": false,
  "properties": {
     "type": { "type": "string" },
     "id": { "type": "string" }
  }
}

{
  "$schema" : "https://json-schema.org/draft/2020-12/schema",
  "title" : "MultipleChoiceQuestion",
  "allOf": [
    { "$ref": "./QuestionBase.schema.json" },
    {
      "type" : "object",
      "requiredProperties": [ "choices" ],
      "additionalProperties": false,
      "properties": {
         "type": { "type": "string", "enum": [ "multiple_choice" ] },
         "choices": { "type": "array", "items": { "type": "string" } },
      }
   }
 ]
}

We should get something like this

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type"
    )
@JsonSubTypes({
  @JsonSubTypes.Type(value = MultipleChoiceQuestion.class, name = "multiple_choice"),
  @JsonSubTypes.Type(value = SimpleAnswerQuestion.class, name = "simple_answer")
})
// note interface if it detects there's nothing in the JSON specific to Question, it's just oneOf and additionalProperties = false
interface Question {}

trajano avatar Dec 11 '24 13:12 trajano