2009-06-29 97 views
0

我已经创建了一个XML模式,通过注释现有的Java域模型类,现在当我尝试使用JAXB解组在我的restlet webservice中收到的表示时我得到错误无论我似乎尝试。我是新来的都restlets和JAXB这样指着我同时使用将是有益的体面的例子的方向只有一个,我设法找到至今在这里:Example在restlet的acceptRepresentation方法中使用JAXB解组XML使用JAXB

我的错误是:

如果我尝试使用restlet.ext.jaxb JaxbRepresentation:

@Override 
public void acceptRepresentation(Representation representation) 
    throws ResourceException { 
JaxbRepresentation<Order> jaxbRep = new JaxbRepresentation<Order>(representation, Order.class); 
jaxbRep.setContextPath("com.package.service.domain"); 

Order order = null; 

try { 

    order = jaxbRep.getObject(); 

}catch (IOException e) { 
    ... 
} 

从此我在jaxbRep.getObject()

得到 java.io.IOException: Unable to unmarshal the XML representation.Unable to locate unmarshaller. 例外,所以我阿尔斯Ø尝试了不同的方法,看看是否能带来差异,使用下面的代码来代替:

@Override 
public void acceptRepresentation(Representation representation) 
    throws ResourceException { 

try{ 

    JAXBContext context = JAXBContext.newInstance(Order.class); 

    Unmarshaller unmarshaller = context.createUnmarshaller(); 

    Order order = (Order) unmarshaller.unmarshal(representation.getStream()); 

} catch(UnmarshalException ue) { 
    ... 
} catch(JAXBException je) { 
    ... 
} catch(IOException ioe) { 
    ... 
} 

然而,这也给了我下面的异常是由调用JAXBContext.newInstance时。

java.lang.NoClassDefFoundError: javax/xml/bind/annotation/AccessorOrder 

在此先感谢您的任何建议。

回答

0

似乎还有一对夫妇的错误在这里,我从未有过的ObjectFactory类,我用了JAXB库的最新版本,加入这个类,并更新到2.1.11后,似乎现在的工作

0

Jaxb Extension for Restlet对我也不适用。我得到了相同的Unable to marshal异常以及一些更多的异常。奇怪的是JAXBContext.newInstance()调用本身在我的代码中正常工作。因此,我写了一个简单的JaxbRepresenetation类:

public class JaxbRepresentation extends XmlRepresentation { 

private String contextPath; 
private Object object; 

public JaxbRepresentation(Object o) { 
    super(MediaType.TEXT_XML); 
    this.contextPath = o.getClass().getPackage().getName(); 
    this.object = o; 
} 

@Override 
public Object evaluate(String expression, QName returnType) throws Exception { 
    final XPath xpath = XPathFactory.newInstance().newXPath(); 
    xpath.setNamespaceContext(this); 

    return xpath.evaluate(expression, object, returnType); 

} 

@Override 
public void write(OutputStream outputStream) throws IOException { 
    try { 
     JAXBContext ctx = JAXBContext.newInstance(contextPath); 
     Marshaller marshaller = ctx.createMarshaller(); 
     marshaller.marshal(object, outputStream); 
    } catch (JAXBException e) { 
     Context.getCurrentLogger().log(Level.WARNING, "JAXB marshalling error!", e); 
     throw new IOException(e); 
    } 
} 
} 
+0

为每个write()实例化一个编组器非常昂贵。 Restlet缓存实例化,只发生一次。我认为问题可能是Restlet绑定到独立的jaxb jar而不是使用JRE中捆绑的实现。我要调查此问题,因为它会在App Engine上导致问题。 – ZiglioUK 2012-08-09 12:51:29