I am trying to serialize a parent
which contains a list of child
s. These child
s have an activated
boolean field, and I want that the resulting XML contains only the child
s wich an activated
attribute set to true
I could do this by copying the parent
object and filtering the child
s in the process (and I may do this at the end) but I am wondering if it is possible to customize SimpleXML to have the same result.
EDIT
I used the response given by ollo. I just changed the Converter
implementation for using the original annotations of the child classes.
The new Converter
implementation:
public class ChildConverter implements Converter<Child>
{
@Override
public Child read(InputNode node) throws Exception
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void write(OutputNode node, Child value) throws Exception
{
if( value.isActived() == true ) // Check if 'activated' flag is set
{
// Set valus of the child
//We don't use an annotation strategy for this persister to avoid
//a recursive call to this method.
Serializer serializer = new Persister();
serializer.write(value, node);
}
else
{
node.remove(); // Remove the node since we don't need it
}
}
}
Some more informations (code, expected XML etc.) would be helpful ...
But here's an example how you can do this:
The key feature is implementing a
Converter
, where you can customize how objects are serialized / deserialized. In the following code I implement aConverter
for theChild
class, however it's possible to implement it for theParent
class instead too.The
Child
class:Beside the
activated
flag this class has two other members to show how do serialize them.The
Parent
class:The
Converter
implementation:The implementation is not very complex so far. First we check if
activated
is set. If yes we fill the objects value into the node, if it's not set we remove the node (else you'll get a<child />
in your XML).How to use:
And finally ...
The XML output:
There are only
child
elements for object whereactivated
wastrue
, those withfalse
are skipped.Note: If you want to remove
class="java.util.ArrayList"
please see here: Remove class= attribute