一般的解决方案是使用自定义模块。您可以定义要用于集合的类。 Guava 有一个 Maven 模块:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>x.y.z</version>
</dependency>
现在,您可以注册新模块了:
ObjectMapper mapper = new ObjectMapper();
// register module with object mapper
mapper.registerModule(new GuavaModule());
现在,您可以在您的POJO 中定义您想要的列表的不可变实现。
class Pojo {
private ImmutableList<Integer> ints;
public ImmutableList<Integer> getInts() {
return ints;
}
public void setInts(ImmutableList<Integer> ints) {
this.ints = ints;
}
@Override
public String toString() {
return "Pojo{" +
"ints=" + ints + " " + ints.getClass() + '}';
}
}
以下示例:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new GuavaModule());
String json = "{\"ints\":[1,2,3,4]}";
System.out.println(mapper.readValue(json, Pojo.class));
打印:
Pojo{ints=[1, 2, 3, 4] class com.google.common.collect.RegularImmutableList}
如果您不想将POJO 类与List 实现绑定,您需要使用SimpleModule 类添加一些额外的配置。因此,您的 POJO 如下所示:
class Pojo {
private List<Integer> ints;
public List<Integer> getInts() {
return ints;
}
public void setInts(List<Integer> ints) {
this.ints = ints;
}
@Override
public String toString() {
return "Pojo{" +
"ints=" + ints + " " + ints.getClass() + '}';
}
}
您的示例如下所示:
SimpleModule useImmutableList = new SimpleModule("UseImmutableList");
useImmutableList.addAbstractTypeMapping(List.class, ImmutableList.class);
GuavaModule module = new GuavaModule();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
mapper.registerModule(useImmutableList);
String json = "{\"ints\":[1,2,3,4]}";
System.out.println(mapper.readValue(json, Pojo.class));
上面的代码打印:
Pojo{ints=[1, 2, 3, 4] class com.google.common.collect.RegularImmutableList}
当你删除额外的SimpleModule 上面的代码打印时:
Pojo{ints=[1, 2, 3, 4] class java.util.ArrayList}
如果Collections.emptyList() 为空,我认为没有任何意义。 Guava 的模块使用 RegularImmutableList 表示非空和空数组。
要转换null -> empty,请参阅此问题:
- Jackson deserializer - change null collection to empty one
但我建议在POJO 中将其设置为empty,如下所示:
private List<Integer> ints = Collections.emptyList();