Published
Reading time ∼1 mins

Parsing varargs as array with Jackson

Consider the following Java class where the setter for the author property accepts the values as varargs.

class Book {
  private String[] author;

  public String[] getAuthor() {
    return this.author;
  }

  public void setAuthor(String... author) {
    this.author = author;
  }
}

If you pass a single value of the author as follows, Jackson will throw an error.

{
  "author": "Jenny McLachlan"
}

To enable Jackson accept a single value as an array, you can use @JsonFormat annotation as follows.

class Book {
  @JsonFormat(with = Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
  private String[] author;

  // getters, setters, etc.
}