[英]Custom Json Deserializer in Jackson for Hashmap only
我正在為Java類的層次結構編寫json序列化(使用Jackson),即這些類由其他類組成。 因為我沒有序列化所有屬性,所以我使用了JsonViews並僅注釋了要序列化的那些屬性。 此層次結構頂部的類包含一個Map,它也需要序列化/反序列化。 是否可以僅為Map編寫序列化器/解串器? 我希望默認的序列化程序負責序列化其余對象
為什么會有這個要求? 如果為最高級的類定義一個序列化器,則需要對所有對象進行序列化。 JsonGenerator對象似乎忽略了JsonView批注,並序列化了所有屬性。
當然有可能。 您可以使用Map類的通用類型定義自定義序列化程序,然后使用Jackson模塊子系統對其進行綁定。
這是一個示例:(它產生了愚蠢的自定義序列化,但是主體有效)
public class Test
{
// the "topmost" class
public static class DTO {
public String name = "name";
public boolean b = false;
public int i = 100;
@JsonView(MyView.class)
public Map<String, String> map; {
map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
}
}
// just to prove it works with views...
public static class MyView {}
// custom serializer for Map
public static class MapSerializer extends JsonSerializer<Map> {
@Override
public void serialize(Map map, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
// your custom serialization goes here ....
gen.writeStartObject();
gen.writeFieldName("map-keys");
gen.writeStartArray();
gen.writeString(map.keySet().toString());
gen.writeEndArray();
gen.writeFieldName("map-valuess");
gen.writeStartArray();
gen.writeString(map.values().toString());
gen.writeEndArray();
gen.writeEndObject();
}
}
public static void main(String[] args) {
SimpleModule module = new SimpleModule();
module.addSerializer(Map.class, new MapSerializer());
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
mapper.registerModule(module);
try {
mapper.writerWithView(MyView.class).writeValue(System.out, new DTO());
} catch (Exception e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.