[英]How to set Jackson's deserialization strategy for Collections to obtain a collection of an Immutable Type
Here is an example of java class.这是一个java类的例子。 I need all the fields to be immutable after deserialization.
我需要所有字段在反序列化后都是不可变的。
It can be done if I set the field type to ImmutableMap
.如果我将字段类型设置为
ImmutableMap
就可以完成。 But can I instruct Jackson to deserialize it into an ImmutableMap
without changing the field type Map
?但是我可以指示 Jackson 在不更改字段类型
Map
的情况下将其反序列化为ImmutableMap
吗?
public class AdCategoryConfigImmute {
private ImmutableMap<String, List<Integer>> sceneMap; // type is immutable explicitly
private Map<String, List<Integer>> trMap;
}
In order to specify the subtype for a particular field needs to be deserialized, you can make use of the @JsonDeserialize
annotation.为了指定需要反序列化的特定字段的子类型,您可以使用
@JsonDeserialize
注释。 Required type needs to be provided through its as
property.需要通过其
as
属性提供所需的类型。
public class AdCategoryConfigImmute {
@JsonDeserialize(as = ImmutableMap.class)
private Map<String, List<Integer>> sceneMap;
// getter, setters
}
But since here we need an ImmutableMap
(or its subtype) from Guava library, you need to register Jackson's GuavaModule
(link to the Maven repository ), otherwise deserialization would fail.但是由于这里我们需要 Guava 库中的
ImmutableMap
(或其子类型),因此您需要注册 Jackson 的GuavaModule
(链接到Maven 存储库),否则反序列化将失败。
Example:例子:
public static void main(String[] args) throws IOException {
String json = """
{
"sceneMap" : {
"foo" : [1, 2, 3]
}
}
""";
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new GuavaModule());
AdCategoryConfigImmute pojo = mapper.readValue(json, AdCategoryConfigImmute.class);
System.out.println(pojo.getSceneMap().getClass());
}
Output:输出:
class com.google.common.collect.SingletonImmutableBiMap
Note: if you're using Spring Boot, it would register the GuavaModule for you while configuring ObjectMapper
at the application start up (no need to register the module it manually, you only need to add a dependency).注意:如果您使用的是 Spring Boot,它会在应用程序启动时配置
ObjectMapper
时为您注册 GuavaModule(无需手动注册模块,您只需要添加依赖项)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.