使用MOxy进行xml绑定,返回null unmarshalled对象

时间:2014-02-12 06:25:49

标签: java xml json jaxb moxy

我正在使用MOXy和相同的域对象模型来生成xml / json。编组和unmarhsalling生成json输出按预期工作,我可以在解组后获取带有所有值的java对象,但解组xml不会给出一个带有所有预期值的java对象,而是给出null值。虽然编组很好。以下是代码

域对象模型

@XmlType(propOrder = {"colour","model","transmission"})
public class BMW {

private String colour;
private String model;
private String transmission;

@XmlPath("Cars/BMW/colour/text()")
public void setColour(String colour){
    this.colour = colour;       
}
@XmlPath("Cars/BMW/model/text()")
public void setModel(String model){
    this.model = model;     
}
@XmlPath("Cars/BMW/transmission/text()")
public void setTransmission(String transmission){
    this.transmission = transmission;       
}

public String getColour(){
    return this.colour;
}
public String getModel(){
    return this.model;
}
public String getTransmission(){
    return this.transmission;
}

}

编组和解组的测试方法

    BMW bmw = new BMW();
    bmw.setColour("white");
    bmw.setModel("X6");
    bmw.setTransmission("AUTO");
    File fileXML = new File("/..../bmw.xml");
    File fileJson = new File("/..../bmw.json");
    XMLInputFactory xif = XMLInputFactory.newInstance();
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(BMW.class);
        Marshaller m = jaxbContext.createMarshaller();
        Unmarshaller um = jaxbContext.createUnmarshaller();         
//=====         XML
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(bmw, fileXML);
        m.marshal(bmw, System.out); 
        StreamSource xml = new StreamSource(fileXML);
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);
//          xsr.nextTag();
//          xsr.nextTag();
        BMW bmwXML = (BMW)um.unmarshal(xsr,BMW.class).getValue();

//====          JSON
        m.setProperty("eclipselink.json.include-root", false);
        m.setProperty("eclipselink.media-type", "application/json");         
        um.setProperty("eclipselink.media-type", "application/json");
        um.setProperty("eclipselink.json.include-root", false);  
        m.marshal(bmw, fileJson);
        m.marshal(bmw, System.out);
        StreamSource json = new StreamSource(fileJson)
        BMW bmwJson = um.unmarshal(json, BMW.class).getValue();         
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

从上面的代码中我可以看到,我尝试过使用xsr.NextTag()但没有帮助。

因此bmwXML具有所有空值,而bmwJson工作正常。不确定我做错了什么。

1 个答案:

答案 0 :(得分:0)

编组到XML时,您没有为BMW类提供根元素信息。这意味着您需要执行以下操作之一:

  1. 使用BMW

    注释@XmlRootElement
    @XmlRootElement
    @XmlType(propOrder = {"colour","model","transmission"})
    public class BMW {
    
  2. 在编组之前,将BMW的实例包裹在JAXBElement中。请注意,当您执行解组时,BMW的实例已包含在JAXBElement中,这就是您所谓的getValue()

    JAXBElement<BMW> je = new JAXBElement(new QName("root-element-name"), BMW.class, bmw);
    m.marshal(je, fileXML);
    
相关问题