今天试着把SpringMVC与fastjson整合了下,经测试也能解决json含中文乱码的问题,特此分享之。我也是初用,详细文档请见官网

转换类:

  1. public class MappingFastJsonHttpMessageConverter extends 
  2.         AbstractHttpMessageConverter<Object> { 
  3.     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 
  4.  
  5.     private SerializerFeature[] serializerFeature; 
  6.  
  7.     public SerializerFeature[] getSerializerFeature() { 
  8.         return serializerFeature; 
  9.     } 
  10.  
  11.     public void setSerializerFeature(SerializerFeature[] serializerFeature) { 
  12.         this.serializerFeature = serializerFeature; 
  13.     } 
  14.  
  15.     public MappingFastJsonHttpMessageConverter() { 
  16.         super(new MediaType("application""json", DEFAULT_CHARSET)); 
  17.     } 
  18.  
  19.     @Override 
  20.     public boolean canRead(Class<?> clazz, MediaType mediaType) { 
  21.         return true
  22.     } 
  23.  
  24.     @Override 
  25.     public boolean canWrite(Class<?> clazz, MediaType mediaType) { 
  26.         return true
  27.     } 
  28.  
  29.     @Override 
  30.     protected boolean supports(Class<?> clazz) { 
  31.         throw new UnsupportedOperationException(); 
  32.     } 
  33.  
  34.     @Override 
  35.     protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) 
  36.     throws IOException, HttpMessageNotReadableException { 
  37.         ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  38.         int i; 
  39.         while ((i = inputMessage.getBody().read()) != -1) { 
  40.             baos.write(i); 
  41.         } 
  42.         return JSON.parseArray(baos.toString(), clazz); 
  43.     } 
  44.  
  45.     @Override 
  46.     protected void writeInternal(Object o, HttpOutputMessage outputMessage) 
  47.     throws IOException, HttpMessageNotWritableException { 
  48.         String jsonString = JSON.toJSONString(o, serializerFeature); 
  49.         OutputStream out = outputMessage.getBody(); 
  50.         out.write(jsonString.getBytes(DEFAULT_CHARSET)); 
  51.         out.flush(); 
  52.     } 

SpringMVC关键配置:

  1. <mvc:annotation-driven> 
  2.     <mvc:message-converters register-defaults="true">        
  3.         <!-- fastjosn spring support --> 
  4.         <bean id="jsonConverter" class="com.alibaba.fastjson.spring.support.MappingFastJsonHttpMessageConverter"> 
  5.             <property name="supportedMediaTypes" value="application/json" /> 
  6.             <property name="serializerFeature"> 
  7.                 <list> 
  8.                     <value>WriteMapNullValue</value> 
  9.                     <value>QuoteFieldNames</value> 
  10.                 </list> 
  11.             </property> 
  12.         </bean> 
  13.     </mvc:message-converters> 
  14. </mvc:annotation-driven> 

参考:OSChina FastJSON官网