我想對一個簡單的java類的Marshaller和unMarshaller測試代碼。JAVA - unMarshaller不返回相同的對象 - 代碼示例
我創建我的對象並設置其ID。遇到的問題是解組回Java對象的ID變量是不一樣的後...
我的問題是:
- 爲什麼沒有這方面的工作和這兩個對象不具備相同的ID?
- 我的java類必須有一個所有變量的設置方法?或者Marshaller使用不同的方式來更新類變量?
這是我的代碼片段:
package test;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Test;
public class test {
@Test
public void marshallingTest() throws JAXBException{
// Create a JAXB context passing in the class of the object we want to marshal/unmarshal
final JAXBContext context = JAXBContext.newInstance(JavaObject.class);
// Create the marshaller
final Marshaller marshaller = context.createMarshaller();
// Create a stringWriter to hold the XML
final StringWriter stringWriter = new StringWriter();
// Create my java object
final JavaObject javaObject = new JavaObject();
// set the objects ID
javaObject.setId(90210);
// Marshal the javaObject and write the XML to the stringWriter
marshaller.marshal(javaObject, stringWriter);
// Print out the contents of the stringWriter
System.out.println("First object :");
System.out.println(javaObject.toString());
// Create the unmarshaller
final Unmarshaller unmarshaller = context.createUnmarshaller();
// Unmarshal the XML
final JavaObject javaObject2 = (JavaObject) unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
//print the new object
System.out.println("Second object after unmarshaller :");
System.out.println(javaObject2.toString());
}
@XmlRootElement
private static class JavaObject {
private int id;
public JavaObject() {
}
private int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "id = "+id;
}
}
}
這是輸出:
First object :
id = 90210
Second object after unmarshaller :
id = 0