Search code examples
javajsonjackson

Jackson: serialize / deserialize object with one array field


I have got the following class:

public class Foo {

    private Bar[] bars;

    @JsonCreator
    public Foo(Bar[] bars) {
        this.bars = bar;
    }
}

I would like a serialized json to look like this:

[
  {
    "x": 1,
    "b": "b1"
  },
  {
    "x": 2,
    "b": "b2"
  }
]

where each element in this array is a Bar. I have tried to put @JsonFormat(shape=JsonFormat.Shape.ARRAY) but then the serialized json starts with [[ which probably makes sense, because the whole object then becomes an array.

Is writing a custom serializer the only approach here?


Solution

  • Use com.fasterxml.jackson.annotation.JsonValue annotation. Since version 2.9 you can annotate field, if you use older version annotate getter method.

    @JsonValue
    private Bar[] bars;