11

我尝试使用简单的序列化嵌入式集合。例如 :

Map<String, List<MyClass>>

我已经在 MyClass 中添加了必要的注释,我尝试使用 @ElementMap 但它不起作用: Exception in thread "main" org.simpleframework.xml.transform.TransformException: Transform of class java.util.ArrayList not supported

如果它只是

@ElementMap Map<String, MyClass>

它工作正常。我不知道如何处理嵌入式集合。我知道@ElementList注释,但不知道在这种情况下如何使用它。有什么提示吗?

4

1 回答 1

11

我遇到了同样的问题。我设法让它工作的唯一方法是一个非常俗气的黑客 - 将 List 包装在另一个类中。

public class MyWrapper {

    @ElementList(name="data")
    private List<MyClass> data = new ArrayList<MyClass>();

    public MyWrapper(List<MyClass> data) {
        this.data = data;
    }

    public List<MyClass> getData() {
        return this.data;
    }

    public void setData(List<MyClass> data) {
        this.data = data;
    }

}

然后,而不是

@ElementMap Map<String,List<MyClass>>

...您将拥有:

@ElementMap Map<String,MyWrapper>

In my case, the Map is entirely private to my class (i.e. other classes never get to talk directly to the Map), so the fact that I have this extra layer in here doesn't make much of a difference. The XML that is produced of course, is gross, but again, in my case, it's bearable because there is nothing outside of my class that is consuming it. Wish I had a better solution than this, but at the moment, I'm stumped.

于 2011-02-22T01:07:51.993 回答