将 Jersey 实体记录为 JSON 作为响应
Log Jersey entity as JSON as response
我是 Jersey 新手,我需要记录 JSON 响应。我希望获取实体并将其转换为 JSON ,就像 Jersey 框架所做的那样(相同的映射器等)。有没有办法提取它的映射器(并调用,例如,它的 writeValueAsString)?
你没有指定你使用哪个包来产生 JSON 响应(你也没有解释太多关于你的球衣服务器),但我假设你使用 Jackson
.
你在泽西岛有一些追踪,看看here,但据我所知它不能满足你的需要。
但首先你应该实现一个 LoggingFilter
,
public class YourLoggingFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException {
...
}
}
并且我假设您扩展 ResourceConfig
class 以添加资源,您需要在此处添加新过滤器:
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();
}
希望对您有所帮助。
我是 Jersey 新手,我需要记录 JSON 响应。我希望获取实体并将其转换为 JSON ,就像 Jersey 框架所做的那样(相同的映射器等)。有没有办法提取它的映射器(并调用,例如,它的 writeValueAsString)?
你没有指定你使用哪个包来产生 JSON 响应(你也没有解释太多关于你的球衣服务器),但我假设你使用 Jackson
.
你在泽西岛有一些追踪,看看here,但据我所知它不能满足你的需要。
但首先你应该实现一个 LoggingFilter
,
public class YourLoggingFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException {
...
}
}
并且我假设您扩展 ResourceConfig
class 以添加资源,您需要在此处添加新过滤器:
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();
}
希望对您有所帮助。