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