Search code examples
javajacksonopenapijackson-databindopenapi-generator

Json schema with anyOf field with same name and different types to POJO + Jackson


If have a schema with component A that contains AnyOf section with two items. The difference between them is that in one case child component C is array and in another one C is object but they have the same name B. Is it possible to handle it with jackson if I have two java objects for that?

I'm thinking if I can use interface with some annotations and jackson will determine the correct object...

"A": {
        "type": "object",
        "anyOf": [
          {
            "properties": {
              "B": {
                "type": "array",
                "items": {
                  "type": "object",
                  "$ref": "#/components/schemas/C"
                }
              }
            },
            "additionalProperties": false
          },
          {
            "properties": {
              
              "B": {
                "type": "object",
                "$ref": "#/components/schemas/C"
              }
            },
            "additionalProperties": false
          }
        ]
      }

Lets suppose I have this in java

public class AAnyOf1 {

  @JsonProperty("B")
  private List<C> b = new ArrayList<>();

...

}

public class AAnyOf2 {

  @JsonProperty("B")
  private C b = null;

...

}

Solution

  • This is very popular pattern to send in response a JSON Object instead of JSON Array with one JSON Object. So, instead of:

    {
      "b": [
        {
          "id": 1
        }
      ]
    }
    

    API response looks like:

    {
      "b": {
          "id": 1
        }
    }
    

    Jackson already handle this use case. You need to enable ACCEPT_SINGLE_VALUE_AS_ARRAY feature and you need only one version of POJO:

    class AAnyOf {
    
      @JsonProperty("B")
      private List<C> b;
    
    ...
    
    }