springMvc与fastJson 集成时日期格式的问题

第一种重写方法:
package com.jjs.util;

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

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * 自定义fastJson日期转换格式
 * 将默认的"yyyy-MM-dd HH:mm:ss"格式改为 "yyyy-MM-dd"格式
 * @author jjs
 *
 */
public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter{
	
	private static SerializeConfig mapping = new SerializeConfig();  
	private static String dateFormat;  
	static {  
	    dateFormat = "yyyy-MM-dd";  
	    mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));  
	} 
	
	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		// TODO Auto-generated method stub
		
		OutputStream out = outputMessage.getBody();
        String text = JSON.toJSONString(obj, mapping, this.getFeatures());
        byte[] bytes = text.getBytes(this.getCharset());
        out.write(bytes);
	}
	
}

第二种重写方法:
package com.jjs.util;

import java.io.IOException;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter {

	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		// TODO Auto-generated method stub
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH";
		JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
		super.writeInternal(obj, outputMessage);

	}

}

然后,将springMVC.xml(具体文件名以项目而定) 的配置修改为如下, 引用重写 了writeInternal()方法的类进行json序列化

        
            
            
                
                    
                        text/html;charset=UTF-8
                        application/json
                    
                
                
                    
                    WriteDateUseDateFormat
                        WriteMapNullValue
                        QuoteFieldNames
                    
                
            
        
    


你可能感兴趣的:(springMvc与fastJson 集成时日期格式的问题)