Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: serialize / deserialize object with one array field

Tags:

java

json

jackson

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?

like image 974
naimdjon Avatar asked Jun 16 '26 13:06

naimdjon


1 Answers

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;
like image 111
Michał Ziober Avatar answered Jun 18 '26 03:06

Michał Ziober