I serialize this class using the Simple XML framework:
@Root
public class HowToRenderEmptyTag {
@Element(required=false)
private String nullString;
}
I want to get:
<howToRenderNull>
<nullString/>
</howToRenderNull>
But I get:
<howToRenderNull/>
I have tried assigning an empty string:
@Root
public class HowToRenderEmptyTag {
@Element(required=false)
private String emptyString = "";
}
But then I get one opening and one closing tag:
<howToRenderNull>
<emptyString></emptyString>
</howToRenderNull>
This is not sadly accepted correctly by the client consuming the XML and changing the client is out of scope.
Any ideas on how to get the single empty tag?
You can use a trick here; write a converter for your element which changes the behaviour:
HowToRenderEmptyTag
class:
@Root(name = "howToRenderEmptyTag")
public class HowToRenderEmptyTag
{
@Element(name = "emptyString", required = false)
@Convert(value = EmptyElementConverter.class) // Set the converter for this element
private String nullString;
// ...
}
EmptyElementConverter
class:
public class EmptyElementConverter implements Converter<String>
{
@Override
public String read(InputNode node) throws Exception
{
/* Implement if required */
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void write(OutputNode node, String value) throws Exception
{
/* Simple implementation: do nothing here ;-) */
}
}
You don't have to implement this Converter
for strings - in this example it's optional. You can keep the class generic or implement it for Object
so you can use it for any king of element.
Example:
final File f = new File("test.xml");
HowToRenderEmptyTag example = new HowToRenderEmptyTag("");
Serializer ser = new Persister(new AnnotationStrategy()); // Don't forget AnnotationStrategy here!
ser.write(example, f);
and finally the result:
<howToRenderEmptyTag>
<emptyString/>
</howToRenderEmptyTag>
Since you have used both, I'm not sure if the empty element needs the name emptyString or nullString but it's not a big thing to change it :-)
You no need to create a converter to resolve your problem. All you need to do to get:
<howToRenderNull>
<EmptyNode/>
</howToRenderNull>
is:
@Root
public class HowToRenderEmptyTag {
@Element(name = "emptyNode", required=false)
private EmptyNode emptyNode;
@Root
public static class EmptyNode {}
}
the result:
<howToRenderEmptyTag>
<emptyNode/>
</howToRenderEmptyTag>
Cheers! :)
来源:https://stackoverflow.com/questions/17213382/how-to-serialize-a-null-string-as-a-single-empty-tag