简体   繁体   English

Jackson:用一个数组字段序列化/反序列化 object

[英]Jackson: serialize / deserialize object with one array field

I have got the following class:我有以下 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:我希望序列化的 json 看起来像这样:

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

where each element in this array is a Bar .该数组中的每个元素都是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.我试图输入@JsonFormat(shape=JsonFormat.Shape.ARRAY)但随后序列化的 json 以[[开头,这可能是有道理的,因为整个 object 然后变成一个数组。

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:例如,如果您有一个返回Bar[]数组而不是包装该数组的 Foo object 的 controller 方法,您将得到该响应:

@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.使用com.fasterxml.jackson.annotation.JsonValue注解。 Since version 2.9 you can annotate field, if you use older version annotate getter method.2.9版开始,您可以注释字段,如果您使用旧版本注释 getter 方法。

@JsonValue
private Bar[] bars;

You can create for your self a customised Serializer that will tell Jackson how to serialize your object.您可以为自己创建一个customised Serializer器,它会告诉Jackson如何序列化您的 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在你的 foo class 上告诉jackson使用这个序列化程序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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