シンプルな Java クラスで Marshaller と unMarshaller のテスト コードを試しています。
オブジェクトを作成し、その ID を設定します。発生した問題は、それを unMarshalling して Java オブジェクトに戻した後、ID 変数が同じではありません...
私の質問は次のとおりです。
- これが機能せず、両方のオブジェクトが同じ ID を持っていないのはなぜですか?
- 私の Java クラスは、すべての変数に対して set メソッドを持つ必要がありますか? または、マーシャラーは別の方法を使用してクラス変数を更新しますか?
これは私のコードスニペットです:
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