I'm trying to create a very simple REST server. I just have a test method that will return a List of Strings. Here's the code:
@GET
@Path("/test2")
public List test2(){
List list=new Vector();
list.add("a");
list.add("b");
return list;
}
It gives the following error:
SEVERE: A message body writer for Java type, class java.util.Vector, and MIME media type, application/octet-stream, was not found
I was hoping JAXB had a default setting for simple types like String, Integer, etc. I guess not. Here's what I imagined:
<Strings>
<String>a</String>
<String>b</String>
</Strings>
What's the easiest way to make this method work?
I would've saved time if I found Resteasy Jackson Provider sooner.
Just add the Resteasy Jackson Provider JAR. No entity wrappers. No XML annotations. No custom message body writers.
If you are using maven in the jersey project add below in pom.xml and update project dependencies so that Jaxb is able to detect model class and convert list to Media type application XML:
This can be done MUCH easier using wonderful XStream library. No wrappers, no annotations.
Target XML
Serialization
(
String
alias can be avoided by using lowercasestring
tag, but I used OP's code)Deserialization
Deserialization into ArrayList
Deserialization into String[]
Note, that XStream instance is thread-safe and can be pre-configured, shrinking code amount to one-liners.
XStream can also be used as a default serialization mechanism for JAX-RS service. Example of plugging XStream in Jersey can be found here
For a more general solution, for JAXB-XML serialization of any top level list , which only requires 1 new class to be written, check out the solution given in this question:
Is it possible to programmatically configure JAXB?
Finally I've solved it using
JacksonJaxbJsonProvider
It requires few changes in your Springcontext.xml
and Mavenpom.xml
In your Spring
context.xml
addJacksonJaxbJsonProvider
to the<jaxrs:server>
:In your Maven pom.xml add:
I have encountered this pattern a few times, I found that the easiest way is to define an inner class with JaxB annotations. (anyways, you'll probably want to define the root tag name)
so your code would look something like this
if you work with javax.rs (jax-rs) I'd return Response object with the wrapper set as its entity