Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JAXB to unmarshal/marshal a List<String>

Tags:

java

rest

jaxb

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?

like image 443
User1 Avatar asked Oct 21 '09 20:10

User1


People also ask

How do you Unmarshal string JAXB?

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.

How do you Unmarshal a list of objects?

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.

How does JAXB marshalling work?

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.


2 Answers

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?

like image 122
User1 Avatar answered Sep 28 '22 09:09

User1


@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(); } 
like image 27
Sample Code Avatar answered Sep 28 '22 11:09

Sample Code