关于SpringMVC @ResponseBody 返回数据类型转换问题

spring-mvc版本4.2.5
jackson-databind 2.7.4

自定义JsonSerializer处理类、这里用java.sql.Timestamp类型转换

public class TimestampSerializer extends JsonSerializer {

    @Override
    public void serialize(Timestamp timestamp, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(Tools.date2Str(timestamp, "yyyy-MM-dd HH:mm:ss"));
    }
}

自定义ObjectMapper、ObjectMapper类com.fasterxml.jackson.databind.ObjectMapper

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Timestamp.class, new TimestampSerializer());
        this.registerModule(module);
    }
}

在xml中配置自定义的ObjectMapper类、把该类配置到MappingJackson2HttpMessageConverter中


        
            
                
                    
                        application/json;charset=UTF-8
                    
                
                
                    
                    
                
            
        
    

配置完成后返回的Timestamp类型就会自动转换为yyyy-MM-dd HH:mm:ss格式

你可能感兴趣的:(SpringMvc)