2011-07-11 73 views
2

我有一個RESTful服務客戶端。該服務返回SortedSet<Movie>,其中Movie是一個JAXB註釋類。得到的XML如下所示。JAXB在解組之後創建空TreeSet

在客戶端,我有一個自定義MessageBodyReader如下所示。問題是Unmarshaller總是返回一個空的TreeSet

MovieSetMessageBodyReader.java

@SuppressWarnings("unchecked") 
@Override 
public TreeSet<Movie> readFrom(Class<TreeSet<Movie>> type, 
    Type genericType, Annotation[] annotations, MediaType mediaType, 
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream) 
    throws IOException, WebApplicationException { 
Class<Movie> baseType = Types.getCollectionBaseType(type, genericType); 

try { 
    JAXBContext ctx = JAXBContext.newInstance(type, baseType); 
    JAXBElement<?> element = ctx.createUnmarshaller().unmarshal(
     new StreamSource(entityStream), type); 

    return (TreeSet<Movie>) element.getValue(); 
} catch (JAXBException e) { 
    e.printStackTrace(); 
} 

return null; 
} 

MovieServiceRestEasyClient.java

@GET 
@Consumes("text/xml") 
public SortedSet<Movie> sendRequestByProxy() { 
Map<String, Object> requestAttributes = new HashMap<String, Object>(); 
requestAttributes.put("path", path); 

MovieServiceRestEasy proxy = ProxyFactory.create(
    MovieServiceRestEasy.class, ENDPOINT, requestAttributes); 
ClientResponse<TreeSet<Movie>> response = (ClientResponse<TreeSet<Movie>>) proxy 
    .getMovieSet(path); 
return response.getEntity(TreeSet.class, (new GenericType<TreeSet<Movie>>() {}).getGenericType()); 

} 

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<collection> 
<movie>  
    <genre>Unknown</genre> 
    <name>4.3.2.1</name> 
    <year>2010</year> 
</movie> 
<movie>  
    <genre>Unknown</genre> 
    <name>Battlestar Galactica The Plan</name> 
    <year>2009</year> 
</movie> 
</collection> 

回答

0

你爲什麼不使用POJO舉行的解組/編組值?例如:

import javax.xml.bind.annotation.XmlAttribute; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 


@XmlRootElement(name = "movie") 
public class Movie 
{ 
    @XmlElement 
    String name; 

    @XmlElement 
    String genre;