10

我刚刚开始尝试使用 SimpleXML 进行 Android 开发,并认为它进展顺利,直到遇到障碍。下面的代码产生一个异常

W/System.err(665):org.simpleframework.xml.core.ConstructorException:无法构造内部类

我已经查看了有关内部类的问题,并认为我理解您为什么要使用它们(不是我的必然是故意的),但是尽管移动了我的代码以尝试避免使用,但我仍然有点卡住,希望有任何帮助.

源代码:

public class InCaseOfEmergencyMedAlertAllergiesActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);


    Serializer serializer = new Persister();
    InputStream xmlstream = this.getResources().openRawResource(R.raw.sample_data_allergies);
    try {
        medalertdata allergyObject = serializer.read(medalertdata.class, xmlstream);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    setContentView(R.layout.allergies);
}

@Root
public class medalertdata {
    @ElementList
    private List<allergy> allergyList;

    public List getAllergies() {
        return allergyList;
    }
}

@Root
public class allergy{

    @Element
    private String to;

    @Element
    private Boolean medical;

    @Element
    private String notes;

    public allergy(String to, Boolean medical, String notes){
        this.to = to;
        this.medical = medical;
        this.notes = notes;
    }

    public String getTo() {
        return to;
    }

    public Boolean getMedical() {
        return medical;
    }

    public String getNotes() {
        return notes;
    }


}

}

引用的 XML 文件结构如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<medalertdata>
<allergy>
    <to>Penicillin</to>
    <medical>true</medical>
    <notes></notes>
</allergy>
<allergy>
    <to>Bee Stings</to>
    <medical>false</medical>
    <notes>Sample</notes>
</allergy>
</medalertdata>

是我如何注释 SimpleXML 类或我试图阅读它们的问题吗?谢谢!

4

2 回答 2

15

我在将一些深度嵌套的 XML 数据读入 Java 对象时也遇到了这个问题(并希望通过在同一个文件中定义类来保持对象结构简单)。

解决方案(不涉及拆分为单独的文件)是使嵌套类static。(换句话说,将内部类转换为静态嵌套类。)回顾起来有点明显。

例子;
嵌套结构:

// ScoreData
//   Sport
//     Category
//       Tournament

爪哇:

@Root
public class ScoreData {

    @ElementList(entry = "Sport", inline = true)
    List<Sport> sport;

    static class Sport {
        @ElementList(entry = "Category", inline = true)
        List<Category> category;
    }

    // ...
}

免责声明:我意识到 OP 已经解决了问题,但也许这可以帮助其他遇到 org.simpleframework.xml.core.ConstructorException: Can not construct inner class并且不想像彼得的回答所暗示的那样在单独的文件中定义类的人。

于 2013-04-17T14:38:22.670 回答
6

尝试@Rootallergy班级中删除。

另外:你在它的单独文件中是否有这两个类:allergy.java 和medalertdata.java?

于 2011-12-10T19:20:33.313 回答