1

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;

...

}
Forgery
  • 88
  • 6

1 Answers1

1

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;

...

}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); It helps me! Thank you! – Forgery Sep 23 '20 at 06:21
  • @Forgery, I'm glad to hear that! Similar questions: [com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token](https://stackoverflow.com/questions/58539657/com-fasterxml-jackson-databind-exc-mismatchedinputexception-cannot-deserialize), [How to enforce ACCEPT_SINGLE_VALUE_AS_ARRAY in jackson's deserialization process using annotation](https://stackoverflow.com/questions/39041496/how-to-enforce-accept-single-value-as-array-in-jacksons-deserialization-process) – Michał Ziober Sep 23 '20 at 06:56
  • 1
    since jackson version 2.7.0 we can also use: @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) – Forgery Sep 23 '20 at 08:59