2017-03-28 72 views
0

我想解組以下的XML,但得到一個異常:「1計數IllegalAnnotationExceptions EntityVersionInfo沒有一個不-arg默認構造函數。「儘管實際上有一個沒有參數的構造函數。我錯過了什麼?Unmarshalling錯誤Jaxb - 「類沒有默認無參數構造函數」,而有一個默認的無參數構造函數

XML:Java中

<topLevelObject> 
    <entityVersionInfo> 
     <id>111111</id> 
     <version>1</version> 
    </entityVersionInfo> 
</topLevelObject> 

實體註釋:

TopLevelObject:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name = "topLevelObject") 

public class TopLevelObject { 

    @XmlElement(name = "entityVersionInfo") 
    private EntityVersionInfo versionInfo; 

    public TopLevelObject() { 
     //no args constructor 
    } 

    //GETTERS AND SETTERS HERE... 
} 

EntityVersionInfo:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name = "entityVersionInfo") 

public class EntityVersionInfo { 
    @XmlElement(name = "id") 
    private String id; 

    @XmlElement(name = "version") 
    private String version; 

    public EntityVersionInfo() { 
     //no arg constructor 
    } 

    //GETTERS AND SETTERS 
} 

回答

1

添加這EntityVersionInfo

@Override 
public String toString() { 
    return "EntityVersionInfo [id=" + id + ", version=" + version + "]"; 
} 

添加這TopLevelObject

@Override 
public String toString() { 
    return "TopLevelObject [versionInfo=" + versionInfo + "]"; 
} 

運行這個測試,我得到:

JAXBContext context = JAXBContext.newInstance(TopLevelObject.class); 
    Unmarshaller u = context.createUnmarshaller(); 

    Reader reader = new StringReader(
      "<topLevelObject>\r\n" + 
      " <entityVersionInfo>\r\n" + 
      "  <id>111111</id>\r\n" + 
      "  <version>1</version>\r\n" + 
      " </entityVersionInfo>\r\n" + 
      "</topLevelObject>"); 
    Object o = u.unmarshal(new InputSource(reader)); 
    System.out.println(o); 

我得到:

TopLevelObject [versionInfo=EntityVersionInfo [id=111111, version=1]] 

所以你實體代碼是好的,也許你的項目中還有一個EntityVersionInfo類或其他東西,但是實體是好的。

+1

Whelp ...這是令人尷尬的。原來,我的項目中有另一個EntityVersionInfo類。謝謝! –

+1

沒有什麼可羞愧的,有時候最明顯的東西是最難找到的。 – minus

相關問題