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

时间秒杀一切 提交于 2019-12-09 10:19:43

问题


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?


回答1:


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




回答2:


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

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