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?
From a personal blog post, it is not necessary to create a specific
JaxbList < T >
object.Assuming an object with a list of strings:
A JAXB round trip:
Produces the following:
Make sure to add @XmlSeeAlso tag with your specific classes used inside JaxbList. It is very important else it throws HttpMessageNotWritableException
In case anyone of you wants to write a list wrapper for lists containing elements of multiple classes and want to give an individual XmlElement name according to the Class type without Writing X Wrapper classes you could use the
@XmlMixed
annotation. By doing so JAXB names the items of the list according to the value set by the@XmlRootElement
. When doing so you have to specify which classes could possibly be in the list using@XmlSeeAlso
Example:
Possible Classes in the list
Wrapper class
Example:
Result:
Alternatevily you could specify the XmlElement names directly inside the wrapper class using the
@XmlElementRef
annotationUser1's example worked well for me. But, as a warning, it won't work with anything other than simple String/Integer types, unless you add an @XmlSeeAlso annotation:
This works OK, although it prevents me from using a single generic list class across my entire application. It might also explain why this seemingly obvious class doesn't exist in the JAXB package.
I used @LiorH's example and expanded it to:
Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:
Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?