不幸的是,您不能为每个字段设置多个注释,并且@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
写成foo
or FoO
- 只要它是一个 foo。