gpt4 book ai didi

java - 如何在 RESTEasy 中使用通用模板 () 从类生成 XML 响应?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:53 33 4
gpt4 key购买 nike

我有一个通用的 ServiceResponse 类,如下所示:

@XMLRootElement
public class ServiceResponse<T>
{
private T data;
private String error;
//setters n getters

}

从我的 RESTEasy 服务中,我想生成如下的 xml 响应:

List<Customer> customers = someDAO.getCustomers();
ServiceResponse<List<Customer>> resp = new ServiceResponse<List<Customer>>();
resp.setData(customers);
resp.setError("No Error");
return resp;
or return Response.ok().entity(resp).build();

但这是抛出错误,因为没有用于 java.util.List 的 JaxbMarshallWriter。

我可以使用 GenericEntity 类编码列表。

GenericEntity<List<Customer>> entity = new GenericEntity<List<Customer>>(customers){};
Response.ok(entity).build();

但是GenericEntity<ServiceResponse<List<Customer>>>说没有 JaxbMarshallWriter for java.util.List 是行不通的。

是否有任何解决方法可以使用通用模板 (, ) 编码/解码类?

最佳答案

我不确定您的类使用通用模板是否有所不同,但这就是我使用 RESTEasy 生成 XML 响应的方式

这是将保存您的服务响应的类

public class ServiceResponse<T>
{
private T data;
private String error;
//setters n getters
}

这是实际将您的响应转换为 XML 的类。除了接收和生成 XML/JSON 或您正在使用的任何内容之外,此类实际上并没有做太多事情。然后它将请求传递给执行实际工作的类。然而,这是可以回答您的特定问题的类(class)(我相信)。

@Path("/myrestservice")
public class SomeRestService
{
private SomeCoreService coreService;
//getters and setters here

@POST
@Path("/examples/")
@Consumes({MediaType.APPLICATION_XML}) //this consumes XML
@Produces({MediaType.APPLICATION_XML}) //this produces XML
public ServiceResponse<T> exampleFunction(Request request)
{
try
{
//Unwrap the request and take only what you need out
//of the request object here
return this.coreService.examples(request.getStringFromRequest());
}
catch(Exception ex)
{
return new ServiceResponse<T>(Put response error message here);
}
}
}

这是完成所有实际工作的类。

public class SomeCoreService
{
public ServiceResponse<T> examples(String stringFromRequest)
{
//do whatever work you need to do here.
return new ServiceResponse<T>(put whatever you need in the service response here)
}
}

另外,我还没有测试过这些。希望这足以让您了解模式。

关于java - 如何在 RESTEasy 中使用通用模板 (<T>) 从类生成 XML 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10753876/

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