JAVA - unMarshaller不返回相同的对象 - 代码示例

问题描述:

我想对一个简单的java类的Marshaller和unMarshaller测试代码。JAVA - unMarshaller不返回相同的对象 - 代码示例

我创建我的对象并设置其ID。遇到的问题是解组回Java对象的ID变量是不一样的后...

我的问题是:

  1. 为什么没有这方面的工作和这两个对象不具备相同的ID?
  2. 我的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 

的所有字段默认情况下,一个JAXB(JSR- 222)实现将把所有的公共字段和属性视为映射的。您的访问者(获取/设置)方法应该是public,您现在将它们设置为private。或者你可以在你的类上指定@XmlAccessorType(XmlAccessType.FIELD),这告诉JAXB映射可能是私有的字段。

更多信息

试试这个:

@XmlElement  
private void setId(int id) { 
     this.id = id; 
    } 

@XmlRootElement 
    private static class JavaObject { 
     @XmlElement 
     private int id; 

您需要指定哪些字段是xml结构的一部分。

您可以添加@XmlElement如已经被以前的答案建议或使用@XmlACcessorType注释:

@XmlRootElement 
    @XmlAccessorType(XmlAccessType.FIELD) 
    private static class JavaObject { 
    } 

默认将访问你的类