SpringMVC與fastjson整合並同時解決中文亂碼問題

 今天試着把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官網

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章