java - 更改 @Produces(...) 在 Jersey 生产的内容?

标签 java json jersey content-type

我是 Jersey 的新手,想更改以下内容:

@Produces(MediaType.APPLICATION_JSON)

我最终想要做的是确保响应的字符编码设置为 UTF-8。如果我对每个生成 json 的方法都执行此操作,我可以根据具体情况执行此操作。

@Produces("application/json;charset=UTF-8")

我当然希望在我的应用程序中执行一次此操作,并让它在任何地方都可以工作。我的第一个想法是 implement a java filter来修改它,但我无法让它发挥作用。

编辑:所以要100%清楚 - 我想在我的应用程序中以某种全局方式执行此操作一次,并让它影响 Jersey 在我的代码中有 @Produces(MediaType.APPLICATION_JSON) 时生成的所有输出。因此,如果我有 100 个带有 @Produces(MediaType.APPLICATION_JSON) 的方法,那么突然有 100 个方法将使用 UTF-8 编码的内容进行发送。

那么我是否可以替换 @Produces(MediaType.APPLICATION_JSON) 生成的内容?如果不是最终值,我只需将 MediaType.APPLICATION_JSON 更改为我的新值;-)

最佳答案

您可以将其实现为 ContainerResponseFilter,在您感兴趣的特定情况下,它会覆盖 @Produces 注释的行为。

@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class MediaTypeFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        for (Annotation annotation : responseContext.getEntityAnnotations()) {
            filterProducesAnnotation(annotation, responseContext);
        }
    }

    private void filterProducesAnnotation(Annotation annotation, ContainerResponseContext responseContext) {
        if (annotation instanceof Produces) {
            Produces produces = (Produces) annotation;
            filterMediaTypes(produces, responseContext);
        }
    }

    private void filterMediaTypes(Produces produces, ContainerResponseContext responseContext) {
        List<Object> mediaTypes = new ArrayList<Object>();
        for (String mediaType : produces.value()) {
            contentTypes.add(mediaType.equals(MediaType.APPLICATION_JSON) ? mediaType + ";charset=UTF-8" : mediaType);
        }
        responseContext.getHeaders().put("Content-Type", mediaTypes);
    }
}

只需确保在您的 Jersey 应用程序中注册 MediaTypeFilter 即可。

关于java - 更改 @Produces(...) 在 Jersey 生产的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277807/

相关文章:

java - 如何引起左键单击然后关闭线程?

python程序从输入写入json

python - 使用 pandas 从 json 文件中提取数据时, bool 值会自动转换为大写

java - REST Web 服务始终使用 CodenameOne 客户端返回 html

hibernate - java.lang.ClassNotFoundException : javax. ws.rs.client.RxInvokerProvider

java - 404 错误 : Resource not available jersey tomcat

java - 在 POJO 中使用依赖注入(inject)来注入(inject) EJB

java - Android 谷歌地图 v2 不显示指南针和位置图标

java - 使用 iReport 操作甘特图的时间范围

java - 从 JSON 映射到具有不同结构的 java 对象