Simple xml framework deserializing with multiple element names

时光毁灭记忆、已成空白 提交于 2019-12-08 02:36:32

Unfortunately you can't set more than one annotation per field and @Element only supports one name (case sensitive). As an alternative you can deserialize those fields by your own - here's an example how to do this:

@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.");
        }

    }
}

Example usage:

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

Now it doesn't matter if foo is written as foo or FoO - as long it's a foo.

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