2 回答

TA贡献1829条经验 获得超6个赞
我认为不存在这种简单的方法,因为CollectionDeserializer
在解析之前创建集合实例。因此,出于此目的,您需要创建自定义反序列化器。
但我不确定=))

TA贡献1805条经验 获得超9个赞
一般的解决方案是使用自定义模块。您可以定义要用于集合的类。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请参阅此问题:
杰克逊反序列化器 - 将空集合更改为空集合
但我建议将其设置为empty如下POJO所示:
private List<Integer> ints = Collections.emptyList();
添加回答
举报