我正在一个简单的 java 类上尝试 Marshaller 和 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