我应该如何使用 Jackson 将包含一个对象的类型列表的对象属性转换为类型对象的属性?

How should I convert an objects attribute of type list containing one object to an attribute of type object using Jackson?

我有一个如下所示的 POJO:

public class Foo {
   private String name;
   private List<Bar> bars;
   // getters and setters
}

bars 可能是空引用、包含 0 个元素的列表、包含 1 个元素的列表或包含 1 个以上元素的列表。

转换为JSON时,此对象的序列化将如下所示:

{
   "name: "foo",
   "bars: [{}, {}]
}

在列表包含 1 个元素的情况下,我要求 barstype 在序列化时“压缩”为单个对象。 JSON 表示应如下所示:

{
   "name": "foo",
   "bars": {}
}

如何使用 Jackson 实现此目的?

在对文档进行大量挖掘后,我发现 WRITE_SINGLE_ELEMENT_ARRAYS_UNWRAPPED

Override for SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED which will force serialization of single-element arrays and Collections as that single element and excluding array wrapper.

实现非常简单,需要向要序列化的对象添加以下注释:@JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED)

public class Foo {
   private String name;
   @JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED)
   private List<Bar> bars;
   // getters and setters
}

将此注释添加到 Foo 后,JSON 输出为:

{
   "name": "foo",
   "bars": {}
}