kaq*_*qao 10 java generics json jackson jackson-databind
由于外部原因,Map我系统中的所有 java只能作为来自客户端的键值对列表接收,例如 aMap<String, Book>实际上将作为 Json-serialized 接收List<MapEntry<String, Book>>。这意味着我需要自定义我的 Json 反序列化过程以期望这种地图表示。
问题是JsonDeserializer让我实施
deserialize(JsonParser p, DeserializationContext ctxt)
Run Code Online (Sandbox Code Playgroud)
无法访问检测到的应该反序列化的泛型类型的方法(Map<String, Book>在上面的示例中)。如果没有这些信息,我将无法在List<MapEntry<String, Book>>不失去类型安全性的情况下反序列化。
我正在查看Converter但它提供的上下文更少。
例如
public Map<K,V> convert(List<MapToListTypeAdapter.MapEntry<K,V>> list) {
Map<K,V> x = new HashMap<>();
list.forEach(entry -> x.put(entry.getKey(), entry.getValue()));
return x;
}
Run Code Online (Sandbox Code Playgroud)
但这可能会创建危险的映射,ClassCastException在检索时会抛出异常,因为无法检查类型是否实际合理。有没有办法解决这个问题?
作为我期望的一个例子,GsonJsonDeserializer看起来像这样:
T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
Run Code Online (Sandbox Code Playgroud)
即它以一种理智的方式提供对预期类型的访问。
kaq*_*qao 16
直接从作者那里得到了关于杰克逊谷歌组的答案。
要理解的关键是JsonDeserializers 被创建/上下文化一次,并且它们仅在那一刻收到完整的类型和其他信息。要获取此信息,解串器需要实现ContextualDeserializer. 它的createContextual方法被调用来初始化一个反序列化器实例,并且可以访问 ,BeanProperty这也给出了完整的JavaType.
所以它最终可能看起来像这样:
public class MapDeserializer extends JsonDeserializer implements ContextualDeserializer {
private JavaType type;
public MapDeserializer() {
}
public MapDeserializer(JavaType type) {
this.type = type;
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
//beanProperty is null when the type to deserialize is the top-level type or a generic type, not a type of a bean property
JavaType type = deserializationContext.getContextualType() != null
? deserializationContext.getContextualType()
: beanProperty.getMember().getType();
return new MapDeserializer(type);
}
@Override
public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
//use this.type as needed
}
...
}
Run Code Online (Sandbox Code Playgroud)
注册并正常使用:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new MapDeserializer());
mapper.registerModule(module);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2335 次 |
| 最近记录: |