回避策があります。それは美しくはありませんが、コンセプトはここであなたを助けることができます。要素アノテーションの代わりに、オブジェクトをシリアル
化するカスタムを使用できます。Converter
(リスト、テキスト、その他の必要な要素が含まれています)
@Root(name="parent")
@Convert(ExampleConverter.class)
public class Example
{
private String text; // Save the text you want to set ('some text' in your code)
private List<Object> valueUnion;
// Constructor + getter / setter
}
シリアル化は独自のコンバーター()で行われるため、実際には、ここでは@Convert(ExampleConverter.class)
と注釈のみが必要です。@Root
ExampleConverter
(ここでオブジェクトをシリアル化/逆シリアル化します)
public class ExampleConverter implements Converter
{
@Override
public Object read(InputNode node) throws Exception
{
/* TODO: Deserialize your class here (if required). */
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void write(OutputNode node, Object value) throws Exception
{
final Example val = (Example) value;
final List<Object> l = val.getValueUnion();
if( !l.isEmpty() ) // if there are elements, insert their nodes
{
for( Object obj : l )
{
node.getChild("values").setValue(obj.toString());
}
}
else
{
node.getChild("values").setValue(""); // this creates <values></values> if list is empty
}
node.setValue(val.getText()); // Set the text (1)
}
}
(1):他の要素がある場合でもテキストを設定します。ただし、このソリューションはフォーマットを壊す可能性があります。テキストと終了タグは同じ行にあります。これは、新しい行を挿入することで解決できます。
シリアライザーを作成し、戦略を立てて書き込み/読み取り
Serializer ser = new Persister(new AnnotationStrategy()); // 'AnnotationStrategy is important here!
ser.write(...); // write / read
リスト内の要素:
Example t = new Example();
t.setText("abc"); // Set the text
t.getValueUnion().add("value1"); // Add some elements to list
t.getValueUnion().add("value2");
Serializer ser = new Persister(new AnnotationStrategy());
ser.write(t, f); // 'f' is the file to write
出力:
<parent>
<values>value1</values>
<values>value2</values>abc</parent>
リストに要素がない場合:
Example t = new Example();
t.setText("abc"); // Set the text
Serializer ser = new Persister(new AnnotationStrategy());
ser.write(t, f); // 'f' is the file to write
出力:
<parent>
<values></values>abc</parent>
前述のフォーマットの「問題」に注意してください。