ITeye博客

SpringMVC与fastjson整合

benqend · 2012-12-18 10:08 · spring · 编程语言 · Markdown

今天试着把SpringMVC与fastjson整合了下,经测试也能解决json含中文乱码的问题,特此分享之。我也是初用,详细文档请见官网。 转换类: public class MappingFastJsonHttpMessageConverter extends AbstractHttpMessageConverter { 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">
WriteMapNullValue QuoteFieldNames </mvc:message-converters> </mvc:annotation-driven>

Link:http://xyly624.blog.51cto.com/842520/896704

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。