繁体   English   中英

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

[英]Log Jersey entity as JSON as response

我是新泽西州的新手,我需要记录JSON响应。 我希望采用该实体并将其完全转换为Jersey框架所做的操作(相同的映射器等),将其转换为JSON。 有没有办法提取其映射器(并调用它的writeValueAsString)?

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

您在泽西岛有一些寻人踪迹,在这里看看,但是据我所知,它并不能满足您的需求。

但首先您应该实现LoggingFilter

public class YourLoggingFilter implements ContainerResponseFilter {

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

    }

}

我假设您扩展ResourceConfig类以添加资源,则需要在此处添加新的过滤器:

public class YourApplication extends ResourceConfig {

    public YourApplication() {
        super();

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

        packages("...");
    }
}

最后,一种将响应记录在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();
}

希望能帮助到你。

暂无
暂无

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

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