jackson ContextualDeserializer和C

2021-11-11  本文已影响0人  随风_d6a2

ContextualDeserializer和ContextualSerializer 其实就是jackson提供的,当我们需要根据编码解码的字段类型决定解码器编码器的时候,利用ContextualDeserializer和ContextualSerializer 提供的方式,实现替代的作用。

举例说明:
当我们使用emptyStringAsMapDeserializer对某个类,做反序列化的时候,emptyStringAsMapDeserializer根据类型,把序列化器变成可以封装成这个类型的对象的EmptyStringAsMapDeserializer对象;

public class Foo 
{ 
   public static void main(String[] args) throws Exception 
   { 
   EmptyStringAsMapDeserializer<Map<String, ?>> emptyStringAsMapDeserializer = 
    new EmptyStringAsMapDeserializer<Map<String, ?>>(null, new ObjectMapper()); 

   SimpleModule module = new SimpleModule("ThingsDeserializer", Version.unknownVersion()); 
   module.addDeserializer(Map.class, emptyStringAsMapDeserializer); 

   ObjectMapper mapper = new ObjectMapper().withModule(module); 

   Person person = mapper.readValue(new File("input.json"), Person.class); 
   System.out.println(mapper.writeValueAsString(person)); 
   } 
} 

class Person 
{ 
   public int id; 
   public String name; 
   public Map<String, Car> cars; 
   public Map<String, Bike> bikes; 
} 

class Car 
{ 
   public String color; 
   public String buying_date; 
} 

class Bike 
{ 
   public String color; 
} 

class EmptyStringAsMapDeserializer<T> 
   extends JsonDeserializer<Map<String, ?>> 
   implements ContextualDeserializer<Map<String, ?>> 
{ 
   private Class<?> targetType; 
   private ObjectMapper mapper; 

   EmptyStringAsMapDeserializer(Class<?> targetType, ObjectMapper mapper) 
   { 
   this.targetType = targetType; 
   this.mapper = mapper; 
   } 

   @Override 
   public JsonDeserializer<Map<String, ?>> createContextual(DeserializationConfig config, BeanProperty property) 
    throws JsonMappingException 
   { 
   return new EmptyStringAsMapDeserializer<Object>(property.getType().containedType(1).getRawClass(), mapper); 
   } 

   @Override 
   public Map<String, ?> deserialize(JsonParser jp, DeserializationContext ctxt) 
    throws IOException, JsonProcessingException 
   { 
   JsonNode node = jp.readValueAsTree(); 
   if ("".equals(node.getTextValue())) 
    return new HashMap<String, Object>(); 
   ObjectMapper mapper = new ObjectMapper(); 
   return mapper.readValue(node, mapper.getTypeFactory().constructMapType(Map.class, String.class, targetType)); 
   } 
} 

上一篇 下一篇

猜你喜欢

热点阅读