SpringMVC整合Fastjason时出现中文乱码

解决乱码的方法,实现AbstractHttpMessageConverter,代码如下

public class MappingFastjsonHttpMessageConverter extends 
AbstractHttpMessageConverter<Object> { 
	public static final Charset DEFAULT_CHARSET = Charset.forName("GBK"); 

	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配置

<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
<!--加载刚才写的消息转换-->
				<bean 
class="com.tankiy.util.MappingFastjsonHttpMessageConverter">
					<property name="supportedMediaTypes" value="application/json" />
					<property name="serializerFeature">
						<list>
							<value>WriteMapNullValue</value>
							<value>QuoteFieldNames</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>

 

你可能感兴趣的:(springMVC)