2015-01-26 41 views

回答

4

你可以做一個簡單的Jackson8Module,將允許你做到以下幾點:

ObjectMapper jacksonMapper = new ObjectMapper(); 
Jackson8Module module = new Jackson8Module(); 
module.addStringSerializer(LocalDate.class, (val) -> val.toString()); 
module.addStringSerializer(LocalDateTime.class, (val) -> val.toString()); 
jacksonMapper.registerModule(module); 

的Jackson8Module代碼只是延伸傑克遜SimpleModule提供的Java 8種友好的方法(它可以擴展到支持其他傑克遜模塊方法):

public class Jackson8Module extends SimpleModule { 

    public <T> void addCustomSerializer(Class<T> cls, SerializeFunction<T> serializeFunction){ 
     JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() { 
      @Override 
      public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 
       serializeFunction.serialize(t, jgen); 
      } 
     }; 
     addSerializer(cls,jsonSerializer); 
    } 

    public <T> void addStringSerializer(Class<T> cls, Function<T,String> serializeFunction) { 
     JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() { 
      @Override 
      public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 
       String val = serializeFunction.apply(t); 
       jgen.writeString(val); 
      } 
     }; 
     addSerializer(cls,jsonSerializer); 
    } 

    public static interface SerializeFunction<T> { 
     public void serialize(T t, JsonGenerator jgen) throws IOException, JsonProcessingException; 
    } 
} 

這裏是Jackson8Module的主旨:https://gist.github.com/jeremychone/a7e06b8baffef88a8816

相關問題