package com.kangxiinfo.wechat.common.fastjson;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
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 CustomFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
public final static Charset UTF8 = Charset.forName("UTF-8");
private Charset charset = UTF8;
private SerializerFeature[] features = new SerializerFeature[0];
/** 自定义的filter */
private LongToStringSerializeFilter longToStringSerializeFilter = new LongToStringSerializeFilter();
public CustomFastJsonHttpMessageConverter() {
super();
}
@Override
protected boolean supports(Class> clazz) {
return true;
}
public Charset getCharset() {
return this.charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public SerializerFeature[] getFeatures() {
return features;
}
public void setFeatures(SerializerFeature... features) {
this.features = features;
}
// 重写这个方法
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
OutputStream out = outputMessage.getBody();
// 转json时 加入自定义的Filter
String text = JSON.toJSONString(obj, longToStringSerializeFilter, features);
byte[] bytes = text.getBytes(charset);
out.write(bytes);
}
}