使用简单框架时不调用转换器

Converter is not called when using Simple Framework

这是一个简单的class

@Root(strict = false)
public class Foo{
    @ElementList(entry = "Test", required = false, inline=true)
    @Convert(TestConverter.class)
    public List<MyClass> test = new ArrayList<MyClass>();

    public static class TestConverter implements  Converter<List<MyClass>>
    {
        public List<MyClass> read(InputNode node) {

            return new ArrayList<MyClass>();
        }

        public void write(OutputNode node, List<MyClass> myclass) {
            node.setAttribute("debug", "debug");
        }
    }
}

永远不会调用转换器。任何人都可以对此有所了解吗?

The converter is never called. Could anyone shed some light on this?

这里的原因:序列化器不知道 @Convert。你必须指定一个策略,告诉有一个转换器要使用。

使用其中之一:

使用 AnnotationStrategy:

只需更换...

Serializer ser = new Persister();

Serializer ser = new Persister(new AnnotationStrategy());
//                             |----------------------|

当然每个here都有一个例子。


其他一些问题:

@ElementList(entry = "Test", required = false, inline=true)
@Convert(TestConverter.class)

这可能会失败:

Note that for the above field the Element annotation is required. If this is used with any other XML annotation such as the ElementList or Text annotation then an exception will be thrown.

http://simple.sourceforge.net/download/stream/doc/javadoc/org/simpleframework/xml/convert/Convert.html

只需改用@Element

使用@Override

@Override /* Better use this */
public List<MyClass> read(InputNode node) {
    // ...
}

@Override /* Better use this */
public void write(OutputNode node, List<MyClass> myclass) {
    // ...
}