将Jersey实体记录为JSON作为响应 [英] Log Jersey entity as JSON as response

查看:219
本文介绍了将Jersey实体记录为JSON作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是泽西新手,我需要记录JSON响应。我希望将实体转换为JSON,就像Jersey框架所做的那样(相同的映射器等)。有没有办法提取它的映射器(并调用,例如,它的writeValueAsString)?

I'm a Jersey newbie and I need to log the JSON response. I wish to take the entity and convert it to JSON exactly as done by the Jersey framework does (same mapper, etc.). Is there a way to extract its mapper (and call, for example, its writeValueAsString)?

推荐答案

你没有指定哪个你用来制作JSON响应的包(你没有解释你的球衣服务器),但我假设你使用 Jackson

You don't specify which package you use for producing the JSON response (neither you explain much about your jersey server), but I will assume you use Jackson.

你在泽西岛有一些追踪,看看这里,但我知道它并不能满足您的需求。

You have some tracing in Jersey, take a look here, but as fas as I know it does not do what you need.

但首先你应该实现 LoggingFilter

public class YourLoggingFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
            throws IOException {
        ...

    }

}

我认为你已经扩展了d ResourceConfig 类添加资源,您需要在此处添加新过滤器:

And I assume you extend the ResourceConfig class to add resources, you need to add the new filter here:

public class YourApplication extends ResourceConfig {

    public YourApplication() {
        super();

        register(YourAuthenticationRequestFilter.class, Priorities.AUTHENTICATION);
        register(YourExceptionMapper.class);
        register(YourLoggingFilter.class);

        packages("...");
    }
}

最后,一种在内部记录响应的简单方法 YourLoggingFilter 将是(这里我假设 Jackson ,但这只是一个例子,我不知道你用什么记录器正在使用,但每次请求时都不要打开文件!!!)

And finally, a simple way to log your response inside YourLoggingFilter would be (here I assume Jackson, but this is just an example, I don't know what logger you are using, but don't open a file every time you do a request!!!)

Object obj = responseContext.getEntity();
ObjectMapper om = new ObjectMapper();
File file = new File("...");
try {
    OutputStream out = new FileOutputStream(file);
    om.writeValue(out, obj);
} catch (IOException e) {
    // this could fail but you don't want your request to fail
    e.printStackTrace();
}

希望有所帮助。

这篇关于将Jersey实体记录为JSON作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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