简体   繁体   中英

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 the 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?

If you have, for example, a controller method that return the Bar[] array and not the Foo object that wraps that array, you will have that response:

@GetMapping("test")
public Test[] test() {
   return new Test[] { new Test(), new Test() };
}

Response:

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

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;

You can create for your self a customised Serializer that will tell Jackson how to serialize your object.

public class FooSerializer extends StdSerializer<Foo> {
    public FooSerializer() {
        this(null);
    }

    public FooSerializer(Class<Foo> t) {
        super(t);
    }

    @Override
    public void serialize(Foo value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartArray();

        for (Bar bar : value.getBars()) {
            if (bar != null) {
                jgen.writeObject(bar);
            }
        }

        jgen.writeEndArray();
    }
}

And on your foo class tell jackson to use this serializer

@JsonSerialize(using = FooSerializer.class)
public class Foo { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM