1
我正在使用MOXy和相同的域對象模型來生成xml/json。編組和生成json輸出按照預期工作,我可以在解組之後獲取具有所有值的java對象,但解組xml不會給所有期望值的java對象提供空值。雖然編組工作正常。下面是代碼使用MOxy for xml綁定返回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;
}
}使用XSR
試驗方法編排和反編排
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();
}
}
正如你可以從代碼中看到上面我已經試過.NextTag()但沒有幫助。
所以bmwXML有所有的空值,而bmwJson工作正常。不知道我做錯了什麼。
非常感謝布萊斯,既解決方案爲我工作。 非常感謝您的快速回復。 –