SimpleXml framework - embedded collections

泪湿孤枕 提交于 2019-12-01 15:14:07

问题


I try to serialize embedded collection using simple. For example :

Map<String, List<MyClass>>

I already added necessary annotations in MyClass, i tried with @ElementMap but it doesn't work: Exception in thread "main" org.simpleframework.xml.transform.TransformException: Transform of class java.util.ArrayList not supported

If its just

@ElementMap Map<String, MyClass>

it works fine. I don't know ho to deal with embedded collection. I know about @ElementList annotation but don't know how to use it in this case. Any hints?


回答1:


I'm coming across the same issue. The only way I have managed to get it working has been a really cheesy hack - wrapping List in another class.

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;
    }

}

And then, instead of

@ElementMap Map<String,List<MyClass>>

...you'd have:

@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.



来源:https://stackoverflow.com/questions/5027706/simplexml-framework-embedded-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!