使用Marshaller 把对象转成xml格式,当对象属性为null时,xml不会对应生成空标签,会造成标签缺失。可以使用反射在运行时对于null属性进行操作
public class MarshallerListener extends Marshaller.Listener {
public static final String BLANK_CHAR = "";
@Override
public void beforeMarshal(Object source) {
super.beforeMarshal(source);
Field[] fields = source.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
try {
if (f.getType() == String.class && f.get(source) == null) {
f.set(source, BLANK_CHAR);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
public String toString() {
try {
JAXBContext context = JAXBContext.newInstance(HzBankPayResponse.class);
Marshaller marshaller = context.createMarshaller();
// 是否省略xml头信息(<?xml version="1.0" encoding="gb2312" standalone="yes"?>)
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setListener(new MarshallerListener());
StringWriter writer = new StringWriter();
marshaller.marshal(this, writer);
return writer.toString();
} catch (JAXBException e) {
return "";
}
}