列挙型をどのようにシリアル化しますか?
このように使用すると、問題なく動作するはずですが、異なる XML が返されます。
例:
@Root
public class Example
{
@Element
private TestStatus status = TestStatus.AVAILABLE;
// ...
}
テスト:
final File f = new File("test.xml");
Serializer ser = new Persister();
ser.write(new Example(), f);
Example m = ser.read(Example.class, f);
XML:
<example>
<status>AVAILABLE</status>
</example>
注釈引数を使用して xml タグの名前を変更できますが、値は変更できません。
別の (可能な) 解決策は、カスタム コンバーターを使用することです。
列挙型の注釈:
@Root()
@Convert(TestStatusConverter.class)
public enum TestStatus
{
// ...
}
コンバーター(例)
public class TestStatusConverter implements Converter<TestStatus>
{
@Override
public TestStatus read(InputNode node) throws Exception
{
final String value = node.getNext("status").getValue();
// Decide what enum it is by its value
for( TestStatus ts : TestStatus.values() )
{
if( ts.getStatus().equalsIgnoreCase(value) )
return ts;
}
throw new IllegalArgumentException("No enum available for " + value);
}
@Override
public void write(OutputNode node, TestStatus value) throws Exception
{
// You can customize your xml here (example structure like your xml)
OutputNode child = node.getChild("status");
child.setValue(value.getStatus());
}
}
テスト (列挙型):
final File f = new File("test.xml");
// Note the new Strategy
Serializer ser = new Persister(new AnnotationStrategy());
ser.write(TestStatus.AVAILABLE, f);
TestStatus ts = ser.read(TestStatus.class, f);
System.out.println(ts);
テスト (列挙型のクラス):
上記と同様ですが、AnnotationStrategy