我想為地圖使用自定義序列化程式,但前提是它們是 <String, String> 地圖。我試圖按照這篇文章StdSerializer<Map,String, String>>中的建議注冊一個,如下所示:
ObjectMapper om = new ObjectMapper();
SimpleModule maskModule = new SimpleModule();
JavaType mapType =
om.getTypeFactory().constructMapLikeType(Map.class, String.class, String.class);
maskModule.addSerializer(new MapSerializer(mapType));
om.registerModule(maskModule);
我的序列化器如下所示:
public static class MapSerializer extends StdSerializer<Map<String, String>> {
MapSerializer(JavaType type) {
super(type);
}
@Override
public void serialize(
Map<String, String> value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeStartObject();
for (Map.Entry<String, String> entry : value.entrySet()) {
gen.writeStringField(entry.getKey(), doOtherStuff(entry.getValue()));
}
gen.writeEndObject();
}
}
這在物件上作業得很好Map<String, String>,但不幸的是它也被其他地圖呼叫。如何將自定義序列化程式限制為特定的泛型型別?
uj5u.com熱心網友回復:
感謝@shmosel 的評論,我發現以下解決方案似乎允許我們使用SerializerModifier.
public static class MapSerializerModifier extends BeanSerializerModifier {
@Override
public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc, JsonSerializer serializer) {
if(valueType.getKeyType().getRawClass().equals(String.class) &&
valueType.getContentType().getRawClass().equals(String.class)) {
return new MapSerializer();
}
return serializer;
}
}
然后,不是MapSerializer直接在模塊中注冊,而是注冊修飾符:
SimpleModule maskModule = new SimpleModule();
maskModule.setSerializerModifier(new MapSerializerModifier());
om.registerModule(maskModule);
現在,每個 Map 都會檢查修飾符,并根據物件的型別屬性回傳自定義序列化程式或默認序列化程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437853.html
上一篇:Java中泛型的向下轉換
下一篇:方法參考運算式“精確”的條件
