How to tell castor to marshall a null field to an empty tag?

99封情书 提交于 2019-12-08 02:21:59

问题


I'm marshalling an object that can have some field set to null. I'm using castor with a xml-mapping file for the configuration. The class I'm marshalling is like this:

class Entity {
    private int id;
    private String name;
    private String description; // THIS CAN BE NULL
    /* ... getters and setters follow ... */
}

...and a mapping file like this:

<mapping>
    <class name="Entity">
        <field name="id" type="integer"/>
        <field name="name" type="string"/>
        <field name="description" type="string"/>
    </class>
</mapping>

What I'm getting at the moment if the field is null (simplified example):

<entity>
   <id>123</id>
   <name>Some Name</name>
</entity>

while I want to have an empty tag in the resulting XML, even if the description field is null.

<entity>
   <id>123</id>
   <name>Some Name</name>
   <description /> <!-- open/close tags would be ok -->
</entity>

回答1:


One way to do this is with a GeneralizedFieldHandler. It's a bit of a hack but it will work for other fields that are Strings.

Example:

<mapping>
    <class name="Entity">
        <field name="id" type="integer"/>
        <field name="name" type="string"/>
        <field name="description" type="string" handler="NullHandler"/>
    </class>
</mapping>


public class NullHandler extends GeneralizedFieldHandler {

    @Override
    public Object convertUponGet( Object arg0 )
    {
        if( arg0 == null )
        {
            return "";
        }

        return arg0;
    }

    @Override
    public Object convertUponSet( Object arg0 )
    {
        return arg0;
    }

    @Override
    public Class getFieldType()
    {
        return String.class;
    }

}


来源:https://stackoverflow.com/questions/9176479/how-to-tell-castor-to-marshall-a-null-field-to-an-empty-tag

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