解组错误Jaxb - "类没有默认的无参数构造函数"虽然有一个默认的没有args构造函数

时间:2017-03-28 16:44:20

标签: java xml constructor jaxb

我试图解组以下XML但得到异常:" 1个IllegalAnnotationExceptions计数EntityVersionInfo没有no-arg默认构造函数。"尽管实际上没有args构造函数。我错过了什么?

XML:

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

带有注释的Java实体:

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 个答案:

答案 0 :(得分: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类,但实体很好。