SpringMVC与fastjson整合并同时解决中文乱码问题
原文地址:
http://xyly624.blog.51cto.com/842520/896704
作者: gdonline
标签:SpringMVC json FastJSON
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://xyly624.blog.51cto.com/842520/896704
今天试着把SpringMVC与fastjson整合了下,经测试也能解决json含中文乱码的问题,特此分享之。我也是初用,详细文档请见官网。
转换类:
public class MappingFastJsonHttpMessageConverter extends
AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private SerializerFeature[] serializerFeature;
public SerializerFeature[] getSerializerFeature() {
return serializerFeature;
}
public void setSerializerFeature(SerializerFeature[] serializerFeature) {
this.serializerFeature = serializerFeature;
}
public MappingFastJsonHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
protected boolean supports(Class<?> clazz) {
throw new UnsupportedOperationException();
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputMessage.getBody().read()) != -1) {
baos.write(i);
}
return JSON.parseArray(baos.toString(), clazz);
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
String jsonString = JSON.toJSONString(o, serializerFeature);
OutputStream out = outputMessage.getBody();
out.write(jsonString.getBytes(DEFAULT_CHARSET));
out.flush();
}
}
SpringMVC关键配置:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- fastjosn spring support -->
<bean id="jsonConverter" class="com.alibaba.fastjson.spring.support.MappingFastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="serializerFeature">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
参考:OSChina FastJSON官网
分享到:
相关推荐
springmvc+fastjson 完整示例,下载即可运行
springMVC整合FastJson实现RestFul风格API 源代码
springMVC整合FastJson实现RestFul风格API涉及jar包
SpringMVC配合Fastjson的内存马利用与分析1
SpringMVC+Fastjson+Swagger集成示例完整源码Example。
springMVC框架遇到中文乱码的解决思路汇总,包括从配置到注解的详细描述,帮助开发人员解决spirngMVC中文乱码问题
NULL 博文链接:https://a243570131.iteye.com/blog/2341355
SpringMVC与Hibernate整合所需jar
SpringMVC解决GET请求时中文乱码的问题.rar
springmvc与hibernate整合,包含spring的事务处理
ssm-springMVC-整合Quartz(解决了无法注入service问题).doc
springmvc和mybatis整合
spring+springMVC+Hibernate整合
springMVC和mybatis整合需要的jar包
springmvc与maven整合项目
本篇文章主要介绍了在springmvc中解决FastJson循环引用的问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
SpringMVC与iReport整合开发时的PDF中文显示处理 SpringMVC与iReport整合开发时的PDF中文显示处理
Spring+SpringMVC+MyBatis整合
spring SpringMvc maven mybatis整合,完整示例 包含sql