球衣/默认默认字符编码 [英] Jersey / Rest default character encoding

查看:107
本文介绍了球衣/默认默认字符编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

失败,例如德国umlaute(üöä),将以错误的方式退还.

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);
            }
        }
    }
}

这篇关于球衣/默认默认字符编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆