[英]Jackson: How to use a custom deserializer with @JsonAnySetter annotation?
I have several YAML config files I want to deserialize into a class. The YAML in the files consists of simple name value pairs with no nesting.我有几个 YAML 配置文件,我想反序列化为 class。文件中的 YAML 由没有嵌套的简单名称值对组成。 There's a handful of properties that will have explicit fields, but the rest I just want dumped into a Map.
有一些属性将具有显式字段,但我只想将 rest 转储到 Map 中。
This all works fine, but I also want all the values of the properties that get deserialized into the Map through .add()
to be run through a custom deserializer.这一切都很好,但我还希望通过自定义反序列化程序运行通过
.add()
反序列化为 Map 的属性的所有值。 I've tried using @JsonDeserialize
on the setter value parameter and the setter method itself but Jackson seems to ignore it altogether.我试过在 setter 值参数和 setter 方法本身上使用
@JsonDeserialize
,但 Jackson 似乎完全忽略了它。
Here's how it's set up:这是它的设置方式:
public class ConfigData {
private Map<String, Object> dynamicConfig = new LinkedHashMap<>();
@JsonAnyGetter
public Map<String, Object> getConfig() {
return dynamicConfig;
}
@JsonAnySetter
public void add(String name, @JsonDeserialize(using = FooDeserializer.class) Object value) {
dynamicConfig.put(name, value);
}
@JsonProperty("some_special_property")
public String setSomeSpecialProperty(String value) {
add("some_special_property", value);
}
}
And to deserialize:并反序列化:
public static ConfigData getConfig(URL configResource) throws IOException {
try (InputStream stream = configResource.openStream()) {
ObjectMapper mapper = new YAMLMapper();
return mapper.readValue(new InputStreamReader(stream, StandardCharsets.UTF_8), ConfigData.class);
}
}
I discovered the problem was that I was specifying the deserializer class with the using
property of the @JsonDeserialize
annotation.我发现问题是我使用
@JsonDeserialize
注释的using
属性指定反序列化器 class。 For this specific use case I needed to use the contentUsing
property instead, which is used for things like the value field of a Map entry.对于这个特定的用例,我需要改用
contentUsing
属性,它用于诸如 Map 条目的值字段之类的东西。
This is what my setter looks like now:这就是我的二传手现在的样子:
@JsonAnySetter
@JsonDeserialize(contentUsing = FooDeserializer.class)
public void add(String name, Object value) {
dynamicConfig.put(name, value);
}
Now all the values will be serialized using FooDeserializer
, except for "some_special_property"
which has its own setter.现在所有的值都将使用
FooDeserializer
序列化,除了"some_special_property"
它有自己的设置器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.