定制杰克逊解串器获取当前现场类 [英] Custom Jackson Deserializer Getting Access to Current Field Class
问题描述
我正在尝试为杰克逊编写一个自定义反序列化程序,我想让它成为通用的(在任何类型的工作意义上都是通用的,而不是在泛型中)。
I'm trying to write a custom deserializer for Jackson and I want to make it generic (generic in the sense of working on any type, not as in "generics").
但是我似乎无法弄清楚如何处理被反序列化的字段的类型。
However I cannot seem to figure out how to get a handle to the type of the field being deserialized.
例如,我正在寻找一些事情如下所示:
Eg, I'm looking to do something like the following:
@Override
public MyObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Class c = <get type of current field>
// do something with that type
return new SubclassOfC(somedata based on c);
}
具体是获取当前字段的类型部分我一直在努力。
It's specifically the get type of current field part that I have struggled with.
编辑:这是我感兴趣的java字段的类型。
It is the type of the java field I am interested in.
推荐答案
我通过向ObjectMapper添加反序列化器的实现解决了我的特殊问题。例如
I have solved my particular problem by adding an implementation of Deserializers to the ObjectMapper. Eg
Deserializers d = new Deserializers.Base() {
@Override
public JsonDeserializer<?> findEnumDeserializer(Class<?> type, DeserializationConfig config, BeanDescription beanDesc, BeanProperty property)
throws JsonMappingException {
if (property.getType().getContentType() != null)
return new EnumDeserializer(property.getType().getContentType().getRawClass());
return new EnumDeserializer(property.getType().getRawClass());
}
};
mapper.setDeserializerProvider(mapper.getDeserializerProvider().withAdditionalDeserializers(d));
这将返回为每个单独的枚举类型实例化的自定义EnumDeserializer。
This will return my custom EnumDeserializer instantiated for each separate Enum type.
这篇关于定制杰克逊解串器获取当前现场类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!