简体   繁体   English

将Jersey实体记录为JSON作为响应

[英]Log Jersey entity as JSON as response

I'm a Jersey newbie and I need to log the JSON response. 我是新泽西州的新手,我需要记录JSON响应。 I wish to take the entity and convert it to JSON exactly as done by the Jersey framework does (same mapper, etc.). 我希望采用该实体并将其完全转换为Jersey框架所做的操作(相同的映射器等),将其转换为JSON。 Is there a way to extract its mapper (and call, for example, its writeValueAsString)? 有没有办法提取其映射器(并调用它的writeValueAsString)?

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 . 您没有指定用于生成JSON响应的软件包(也没有过多说明球衣服务器),但是我假设您使用的是Jackson

You have some tracing in Jersey, take a look here , but as fas as I know it does not do what you need. 您在泽西岛有一些寻人踪迹,在这里看看,但是据我所知,它并不能满足您的需求。

But first of all you should implement a LoggingFilter , 但首先您应该实现LoggingFilter

public class YourLoggingFilter implements ContainerResponseFilter {

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

    }

}

And I assume you extend the ResourceConfig class to add resources, you need to add the new filter here: 我假设您扩展ResourceConfig类以添加资源,则需要在此处添加新的过滤器:

public class YourApplication extends ResourceConfig {

    public YourApplication() {
        super();

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

        packages("...");
    }
}

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!!!) 最后,一种将响应记录在YourLoggingFilter内的简单方法是(这里我假设Jackson ,但这只是一个例子,我不知道您使用的是哪种记录器,但是每次执行操作时都不要打开文件请求!!!)

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

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM