第一种重写方法:
第二种重写方法:
然后,将springMVC.xml(具体文件名以项目而定) 的配置修改为如下, 引用重写 了writeInternal()方法的类进行json序列化
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序列化
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> -->
<bean class="com.jjs.util.JsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<value>WriteDateUseDateFormat</value>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>