SpringMVC的@ResponseBody注解可以将请求方法返回的对象直接转换成JSON对象,但是当返回值是String的时候,中文会乱码。
原因是因为其中字符串转换和对象转换用的是两个转换器,而String的转换器中固定了转换编码为"ISO-8859-1"
解决办法:
1.返回字符串时,将字符串结果转
return new String("你好".getBytes(), "ISO-8859-1");
2.添加@RequestMapping注解,配置produces的值
@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
3.StringHttpMessageConverter重写
public class UTF8StringHttpMessageConverter extends
AbstractHttpMessageConverter
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private final List
private boolean writeAcceptCharset = true;
public UTF8StringHttpMessageConverter() {
super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);
this.availableCharsets = new ArrayList
.availableCharsets().values());
}
/**
* Indicates whether the {@code Accept-Charset} should be written to any
* outgoing request.
*
* Default is {@code true}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
}
@Override
public boolean supports(Class> clazz) {
return String.class.equals(clazz);
}
@Override
protected String readInternal(Class clazz, HttpInputMessage inputMessage)
throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders()
.getContentType());
return FileCopyUtils.copyToString(new InputStreamReader(inputMessage
.getBody(), charset));
}
@Override
protected Long getContentLength(String s, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
try {
return (long) s.getBytes(charset.name()).length;
} catch (UnsupportedEncodingException ex) {
// should not occur
throw new InternalError(ex.getMessage());
}
}
@Override
protected void writeInternal(String s, HttpOutputMessage outputMessage)
throws IOException {
if (writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders()
.getContentType());
FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(),
charset));
}
/**
* Return the list of supported {@link Charset}.
*
*
* By default, returns {@link Charset#availableCharsets()}. Can be
* overridden in subclasses.
*
* @return the list of accepted charsets
*/
protected List
return this.availableCharsets;
}
private Charset getContentTypeCharset(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
return contentType.getCharSet();
} else {
return DEFAULT_CHARSET;
}
}
}
配置文件:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28624388/viewspace-768058/ ,如需转载,请注明出处,否则将追究法律责任。