I have a generic ServiceResponse class as follows:
@XMLRootElement
public class ServiceResponse<T>
{
private T data;
private String error;
//setters n getters
}
From my RESTEasy Service, i want to generate xml response as:
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();
But this is throwing error as there is no JaxbMarshallWriter for java.util.List.
I can marshall List usinig GenericEntity class.
GenericEntity<List<Customer>> entity = new GenericEntity<List<Customer>>(customers){};
Response.ok(entity).build();
But GenericEntity<ServiceResponse<List<Customer>>>
is not working saying no JaxbMarshallWriter for java.util.List.
Is there any work around to marshall/unmarshall classes with generic templates(, )?
I'm not sure if it makes a difference that your class uses generic templates, but this is how I would generate an XML response using RESTEasy
This is the class that would hold your service response
public class ServiceResponse<T>
{
private T data;
private String error;
//setters n getters
}
This is the class that would actually transform your response into XML. This class really doesn't do much other than take in and produce XML/JSON or whatever you are using. It then passes the request on to the class that does the real work. This however is the class that would answer your specific question (I believe).
@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);
}
}
}
This is the class that does all of the real work.
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)
}
}
Also, I haven't tested any of this. Hopefully it is enough for you to get the pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With