gpt4 book ai didi

java - Jax-rs 根据 Jackson 的请求更改序列化响应

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:10 26 4
gpt4 key购买 nike

当前面临一个问题,我想根据传递到响应中的一些信息来更改 jax-rs 资源的响应。需要改变的是一些json的格式。目前我正在使用 jax @Provider 和 ContextResolver 注册一个 ObjectMapper。但是,每个资源类仅调用一次 getContext() 方法。不可能根据每个请求来更改此设置。

是否可以在 ContainerResponseFilter 中注入(inject)或访问 ObjectMapper?

@Provider
public class ObjectMapperResolver implements ContextResolver<ObjectMapper> {

@Context
private HttpServletRequest httpRequest;

private final ObjectMapper mapper;

public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Date.class, new DateDeserializer("some data format"));
mapper.registerModule(module);
}

@Override
public ObjectMapper getContext(Class<?> type) {
return getMapperBasedOnRequest();
}

private ObjectMapper getMapperBasedOnRequest() {
if (true) {
return mapper;
} else {
return //something else;
}
}

private boolean containsLegacyHeader() {
return //get some information from the request headers or body
}
}

最佳答案

我决定通过使用过滤器来解决这个问题,该过滤器将根据请求中提供的参数(在本例中为 header )进行调用。

public class DemoFilter implements ContainerResponseFilter {

private final String UTC = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private final String OTHER = "yyyy-MM-dd";

public static final String DATE_UTC = "utc";

private String getMapperBasedOnRequest(ContainerRequestContext requestContext) {
if (checkHeader(requestContext)) {
return OTHER;
} else {
return UTC;
}
}

private boolean checkHeader(ContainerRequestContext requestContext) {
return //check header
}

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

ObjectWriterInjector.set(new DateMod(getMapperBasedOnRequest(requestContext)));

}

public static class DateMod extends ObjectWriterModifier {

private String df;

public DateMod(String df) {
this.df = df;
}


@Override
public ObjectWriter modify(EndpointConfigBase<?> endpointConfigBase, MultivaluedMap<String, Object> multivaluedMap, Object o, ObjectWriter objectWriter, JsonGenerator jsonGenerator) throws IOException {
return objectWriter.with(new SimpleDateFormat(dateFormat));

}
}

}

关于java - Jax-rs 根据 Jackson 的请求更改序列化响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com