ResponseBody自动转JSON,Date等类的处理

SpringMVC配置@ResponseBody注解时会自动转换为JSON字符串,可像此一样自定义Date或其他类转JSON的格式

代码实现

package data;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * 

Description: ResopnseBody 自动转 JSON 时,特殊类做转换

* * @author c332030 * @version 1.0 * @date 2019-3-21 10:38 */ @Component public class JSONDataFormat extends ObjectMapper { protected Logger logger = LoggerFactory.getLogger(JSONDataFormat.class); private static final ThreadLocal dateTimeFormatThreadLocal = new ThreadLocal() { @Override protected DateFormat initialValue() { return new SimpleDateFormat(defaultDatePattern); } }; public JSONDataFormat() { CustomSerializerFactory factory = new CustomSerializerFactory(); this.setSerializerFactory(factory); dateTimeFormat(factory); } /** * 方法用途: 日期格式化 * 实现步骤: * @param factory * @return void */ public void dateTimeFormat(CustomSerializerFactory factory) { factory.addGenericMapping(Date.class, new JsonSerializer() { @Override public void serialize( Date date, JsonGenerator jsonGenerator, SerializerProvider provider ) throws IOException { jsonGenerator.writeString(dateTimeFormatThreadLocal.get().format(date)); } }); } }

Spring配置文件


        
            
                
                    
                        application/json;charset=UTF-8
                        text/html;charset=UTF-8
                    
                

                
                
            
        
    

你可能感兴趣的:(ResponseBody自动转JSON,Date等类的处理)