使用多个元素名称反序列化的简单xml框架

时间:2013-11-09 14:47:26

标签: java xml xml-deserialization simple-framework

我正在尝试使用Simple XML Framework将一些xml数据从公共Web服务序列化为java对象。 问题是来自服务的不同方法返回具有不同元素名称的相同概念。例如,方法A像这样返回元素foo

<data><Foo>foo value</Foo></data>

而方法B返回

<data><foo>foo value</foo></data>

和方法C返回

<data><FOO>foo value</FOO></data>

是否有任何方法(多重名称注释等)将此xml反序列化为同一个类和相同的元素?例如,将三个方法的结果反序列化为三个不同“Foo”对象中的相同“foo”元素(每个方法一个):

@Root(name="data")
public class Foo{
    @Element
    public String foo;
    (...)
}

1 个答案:

答案 0 :(得分:2)

不幸的是,您不能为每个字段设置多个注释,而@Element仅支持一个名称(区分大小写)。 作为替代方案,您可以自己反序列化这些字段 - 以下是如何执行此操作的示例:

@Root(name = "data")
@Convert(FooConverter.class) // Set the converter that's used for serializing / deserializing this class
public class Foo
{
    @Element( name = "foo") // For this solution it doesn't matter what you set here
    public String foo;

    // ...


    /*
     * The converter - Implement the serialization / deserialization here.
     * You don't have to use an inner class here.
     */
    public static class FooConverter implements Converter<Foo>
    {
        @Override
        public Foo read(InputNode node) throws Exception
        {
            Foo f = new Foo();
            InputNode nextNode = node.getNext();

            while( nextNode != null )
            {
                if( nextNode.getName().equalsIgnoreCase("foo") ) // Here you pick-up the node, however it's written
                {
                    f.setFoo(nextNode.getValue());
                }

                nextNode = node.getNext();
            }

            return f;
        }


        @Override
        public void write(OutputNode node, Foo value) throws Exception
        {
            // Not required in this example.
            throw new UnsupportedOperationException("Not supported yet.");
        }

    }
}

使用示例:

String str = "<data><foo>foo value</foo></data>"; // Foo can be written as you like

Serializer ser = new Persister(new AnnotationStrategy()); // Setting the AnnotationStrategy is important!!
Foo f = ser.read(Foo.class, str);

System.out.println(f);

现在将foo写成fooFoO并不重要 - 只要它是foo。

相关问题