gpt4 book ai didi

jaxb - Jersey/JaxRs 包装任何响应

转载 作者:行者123 更新时间:2023-12-03 17:49:12 27 4
gpt4 key购买 nike

我正在寻找一种方法来包装我的服务的任何响应。

我有一个简单的服务,有很多不同的方法,就像这样

@Path(value = "/listSomething/{apiKey:.+}")
public List<ObjectA> listSomething(@PathParam(value = "apiKey") String apiKey)

一些返回列表,一些只是一些简单的对象。我现在想要实现的是用一些状态信息(例如下面)将这些响应中的任何一个包裹起来。
response {
staus: "OK",
data: {..the actual response..}
}

我试图用一些拦截器来实现这一点,但我没有成功( 除非我添加 @XmlSeeAlso 注释,这是我真正不想要的,因为我想要一些通用方法 )。我的包装类看起来像:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
//@XmlSeeAlso(ResponseA.class)
public class ResponseWrapper {

boolean error;
String message;
@XmlAnyElement(lax = true)
Object object;

public boolean isError() {
return error;
}

public void setError(boolean error) {
this.error = error;
}

public String getMessage() {
return message;
}
}

我尝试了@XmlElement、@XmlAnyElement 的不同组合 - 没有任何成功。我在 WriterInterceptor 和 ContainerResponseFilter 中尝试过。

我该如何做这个简单的技巧(如果我不必关心消费者是想要 XML 还是 JSON 会很酷,但是如果我必须为 JSON 破解一些东西,我可以接受)?

我现在有点失落。谢谢你的帮助。

我通常在尝试的方法中得到的错误是 UNKOWN_CLASS
   {0} nor any of its super class is known to this context.

我的拦截器或多或少是这样做的
  responseContext.setGenericType(Wrapper.class);
responseContext.setType(Wrapper.class);
responseContext.setEntity(wrapperInstance);

最佳答案

我在拦截器中能想到的最简单的方法是:

Object currentEntity = responseContext.getEntity();
ResponseWrapper wrapper = new ResponseWrapper(currentEntity);
responseContext.setEntity(wrapper);

关于jaxb - Jersey/JaxRs 包装任何响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25350799/

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