首页>代码>spring mvc+spring+mybatis+maven+easyui项目整合代码demo>/ssmeasyui/src/main/java/com/dream/util/FastJsonHttpMessageConverter.java
package com.dream.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 使spring mvc与fastjson结合
 * 
 * 利用@ResponseBody注解返回JSON字符串
 * 
 * @author 孙宇
 * 
 */
public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

	public final static Charset UTF8 = Charset.forName("UTF-8");

	private Charset charset = UTF8;

	private SerializerFeature[] serializerFeature;

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		InputStream in = inputMessage.getBody();

		byte[] buf = new byte[1024];
		for (;;) {
			int len = in.read(buf);
			if (len == -1) {
				break;
			}

			if (len > 0) {
				baos.write(buf, 0, len);
			}
		}

		byte[] bytes = baos.toByteArray();
		if (charset == UTF8) {
			return JSON.parseObject(bytes, clazz);
		} else {
			return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
		}
	}

	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

		OutputStream out = outputMessage.getBody();
		byte[] bytes;

		if (charset == UTF8) {
			if (serializerFeature != null) {
				bytes = JSON.toJSONBytes(obj, serializerFeature);
			} else {
				bytes = JSON.toJSONBytes(obj, SerializerFeature.WriteDateUseDateFormat);
			}

		} else {
			String text;
			if (serializerFeature != null) {
				text = JSON.toJSONString(obj, serializerFeature);
			} else {
				text = JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
			}
			bytes = text.getBytes(charset);
		}

		out.write(bytes);
	}

}
最近下载更多
YUProject  LV8 2022年12月17日
张扬扬109  LV8 2022年11月22日
zlstly  LV7 2022年5月7日
chuxd123  LV5 2022年1月18日
kiritoYCQ  LV5 2021年6月23日
凉城.  LV1 2021年3月26日
小刚_HelloWorld  LV1 2021年1月16日
hdf999  LV12 2021年1月13日
ioysky  LV5 2020年9月9日
aaa最代码  LV14 2020年7月30日
最近浏览更多
李朝磊  LV18 2024年5月31日
LiBaQi  LV2 2023年11月9日
张朕朕  LV3 2023年9月8日
你爹正在加载中  LV4 2023年8月3日
遗留问题  LV2 2023年6月9日
森sdfgf  LV8 2023年6月9日
发顺丰达 2023年5月23日
暂无贡献等级
苏拉德666  LV4 2023年5月13日
2661033436  LV2 2023年4月12日
李亮  LV19 2023年3月6日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友