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?
To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.
public List<T> Unmarshal(List<Entry> entries, Class clazz) { List<T> out = new ArrayList<T>(); T instance; for (Entry e : entries) { try { JAXBContext context = JAXBContext. newInstance(clazz); Unmarshaller unmarsh = context.
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
I used @LiorH's example and expanded it to:
@XmlRootElement(name="List") public class JaxbList<T>{ protected List<T> list; public JaxbList(){} public JaxbList(List<T> list){ this.list=list; } @XmlElement(name="Item") public List<T> getList(){ return list; } }
Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:
@GET @Path("/test2") public JaxbList test2(){ List list=new Vector(); list.add("a"); list.add("b"); return new JaxbList(list); }
Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?
@GET @Path("/test2") public Response test2(){ List<String> list=new Vector<String>(); list.add("a"); list.add("b"); final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { }; return Response.ok().entity(entity).build(); }
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