Jackson 全局设置将数组反序列化为自定义列表实现

默认情况下,Jacksonjava.util.ArrayList用于反序列化 JSON 数组。而不是这个,我想使用自定义实现。例如,ImmutableList如果存在值,或者Collection.emptyList()JSON 数组为空或 null,则为 Guava。

我想为ObjectMapper. 是否有捷径可寻?

PS:我的杰克逊版本是2.9.7


HUWWW
浏览 306回答 2
2回答

肥皂起泡泡

我认为不存在这种简单的方法,因为CollectionDeserializer在解析之前创建集合实例。因此,出于此目的,您需要创建自定义反序列化器。但我不确定=))

Cats萌萌

一般的解决方案是使用自定义模块。您可以定义要用于集合的类。Guava 有一个 Maven 模块:<dependency>&nbsp; &nbsp; <groupId>com.fasterxml.jackson.datatype</groupId>&nbsp; &nbsp; <artifactId>jackson-datatype-guava</artifactId>&nbsp; &nbsp; <version>x.y.z</version></dependency>现在,您可以注册新模块:ObjectMapper mapper = new ObjectMapper();// register module with object mappermapper.registerModule(new GuavaModule());现在,您可以在您POJO想要的列表中定义不可变的实现。class Pojo {&nbsp; &nbsp; private ImmutableList<Integer> ints;&nbsp; &nbsp; public ImmutableList<Integer> getInts() {&nbsp; &nbsp; &nbsp; &nbsp; return ints;&nbsp; &nbsp; }&nbsp; &nbsp; public void setInts(ImmutableList<Integer> ints) {&nbsp; &nbsp; &nbsp; &nbsp; this.ints = ints;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "Pojo{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "ints=" + ints + " " + ints.getClass() + '}';&nbsp; &nbsp; }}和下面的例子: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 {&nbsp; &nbsp; private List<Integer> ints;&nbsp; &nbsp; public List<Integer> getInts() {&nbsp; &nbsp; &nbsp; &nbsp; return ints;&nbsp; &nbsp; }&nbsp; &nbsp; public void setInts(List<Integer> ints) {&nbsp; &nbsp; &nbsp; &nbsp; this.ints = ints;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "Pojo{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "ints=" + ints + " " + ints.getClass() + '}';&nbsp; &nbsp; }}您的示例如下所示: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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java