如何告诉castor将一个空字段编组为一个空标签? [英] How to tell castor to marshall a null field to an empty tag?
问题描述
我正在整理一个可以将某些字段设置为null的对象.我正在使用带有xml映射文件的castor进行配置.我正在编组的课程是这样的:
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>
尽管我希望在结果XML中有一个空标记,即使description字段为null.
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>
推荐答案
一种方法是使用GeneralizedFieldHandler.有点hack,但是它可以用于其他字符串类型的字段.
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.
示例:
<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;
}
}
这篇关于如何告诉castor将一个空字段编组为一个空标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!