Jersey / Rest default character encoding(Jersey/Rest 默认字符编码)
问题描述
Jersey 在返回 JSON 时似乎失败了...
这个:
Jersey seems to fail when returning JSON...
This:
@GET
@Produces( MediaType.APPLICATION_JSON + ";charset=UTF-8")
public List<MyObject> getMyObjects() {
return ....;
}
需要返回 JSON utf-8 编码.如果我只使用
is needed to return JSON utf-8 encoded. If I use only
@Produces( MediaType.APPLICATION_JSON)
失败,例如德语变音符号 (üöä),将以错误的方式返回.
fails and for example German umlaute (üöä), will be returned in a wrong way.
两个问题:
1 - 对于 JSON utf-8 ist 标准 - 为什么不使用 Jersey?
2 - 如果有 JSON 请求进来,我可以为整个 REST-Servlet 设置 utf-8 吗?
我在 Android 上使用 Jersey 1.5 和 Crest 1.0.1...
Two questions:
1 - For JSON utf-8 ist standard - why not with Jersey?
2 - Can I set utf-8 for the whole REST-Servlet if a JSON Request comes in?
I am using Jersey 1.5 and CRest 1.0.1 on Android...
推荐答案
SRG 的建议很有魅力.然而,由于 Jersey 2.0 的接口略有不同,所以我们不得不稍微调整一下过滤器:
SRGs suggestion works like a charm. However, since Jersey 2.0 the interfaces are slightly different, so we had to adapt the filter a little bit:
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
public class CharsetResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
MediaType type = response.getMediaType();
if (type != null) {
String contentType = type.toString();
if (!contentType.contains("charset")) {
contentType = contentType + ";charset=utf-8";
response.getHeaders().putSingle("Content-Type", contentType);
}
}
}
}
这篇关于Jersey/Rest 默认字符编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jersey/Rest 默认字符编码
基础教程推荐
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
