使用simpleframework进行XML到java对象的转换



我正在使用simpleframework将xml文件转换为java对象。我使用泛型,因为我的xml的内部节点得到改变。但是simpleframework在转换时抛出错误。下面是我的示例代码:

@Root(name = "searchresult", strict = false)
public class ResponseVO<T>
{
    @ElementList(entry = "document", inline = true)
    public List<T> elementVOList = new ArrayList<T>();
    public List<T>  getElementsVOList()
    {
        return elementVOList;
    }
    public void setElementsVOList(List<T>list)
    {
        elementVOList = list;
    }
}

ResponseVO是以下各种其他vo的容器:

@Root(name = "document", strict = false)
public class Projects_Display_VO
{
    @Element(name = "projectname")
    private String projectName;

    @Attribute(name = "id")
    private int tmpid;
    public int getTmpid()
    {
        return tmpid;
    }
    public void setTmpid(int tmpid)
    {
        this.tmpid = tmpid;
    }
    /**
     * ProjectId
     */
    @Element(name = "projectid")
    private String projectID;

    public String getProjectName()
    {
        return projectName;
    }
    public void setProjectName(String projectName)
    {
        this.projectName = projectName;
    }
    public int getProjectID()
    {
        return Integer.parseInt(projectID);
    }
    public void setProjectID(String projectID)
    {
        this.projectID = projectID;
    }
}

XML文件如下所示:

<searchresult>
  <query>id:(PROJ2 PROJ6)</query>
  <document id="0">
    <projectid>2</projectid>
    <projectname>Redundant Demo Project</projectname>
    <doctype>Projects</doctype>
    <summary>||Demo Project</summary>
    <title>Redundant Demo Project</title>
  </document>
  <document id="1">
    <projectid>6</projectid>
    <projectname>Redundant Demo Project2</projectname>
    <doctype>Projects</doctype>
    <summary>||Main terminal links.</summary>
    <title>Terminal 5 Project</title>
  </document>  
</searchresult>

转换代码如下:

ResponseVO<Projects_Display_VO> resp = (ResponseVO<Projects_Display_VO>)  SerializationUtil.deserialize(ResponseVO.class, reader);

这里我使用的是来自simpleframework的序列化器。但是它会抛出以下错误

Exception::Attribute 'id' does not have a match in class java.lang.Object at line 5
org.simpleframework.xml.core.AttributeException: Attribute 'id' does not have a match in   class java.lang.Object at line 5
at org.simpleframework.xml.core.Composite.readAttribute(Composite.java:555)
at org.simpleframework.xml.core.Composite.readAttributes(Composite.java:474)
at org.simpleframework.xml.core.Composite.readSection(Composite.java:387)
我不知道这里出了什么问题。没有泛型也可以。提前感谢

这是由擦除引起的,T在运行时不可用。Java不允许。

最新更新