class NullConverter implements Converter{
@Override
public boolean canConvert(Class type) {
//false,使用xstream默认转换方式,true使用自定义方式 【注意!!】
return true;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
try {
Class<?> cls = source.getClass();
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(cls);
for (int i = descriptors.length-1; i >= 0; i--) { //因为反射机制,所以得反着写(^ v ^),生成的报文顺序才能和实体对象一致
String key = descriptors[i].getName(); //属性名
String type = descriptors[i].getPropertyType().getTypeName(); //属性类型
Object value = propertyUtilsBean.getNestedProperty(source, key); //属性值
if(!"class".equals(key)){
if("java.lang.String".equals(type)|| "byte".equals(type)
||"char".equals(type)|| "int".equals(type)
||"float".equals(type)|| "long".equals(type)
||"double".equals(type)|| "Enum".equals(type)){
writer.startNode(key);
writer.setValue(value== null ? "" : value.toString());
writer.endNode();
}
else if("java.util.List".equals(type)){
//遍历List集合
if(value instanceof List){
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>)value;
writer.startNode(key); //输入字段前半部分<bodyList>
for (Object object : list) {
marshal(object,writer,context); //输入中间节点内容
}
writer.endNode();//输入字段后半部分</bodyList>
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
// TODO Auto-generated method stub
return null;
}
在xstream.toXML(obj);之前调用xstream.registerConverter(new NullConverter());