How to serialize a null string as a single empty tag?

烂漫一生 提交于 2019-12-03 14:06:00

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! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!