Java – xStream serializes null values
Suppose I have
class Student
{
String name;
int age;
String teacher;
}
then:
public class App1
{
public static void main(String[] args)
{
Student st = new Student();
st.setName("toto");
XStream xs = new XStream();
xs.alias("student",Student.class);
System.out.println(xs.toXML(st));
}
}
Give me:
<student> <name>toto</name> <age>0</age> </student>
Is there any way to handle null values? Well, I mean:
<student> <name>toto</name> <age>0</age> <teacher></teacher> </student>
If I do, maybe
st.setTeacher("");
But if the teacher is empty, then No
I try to use a custom converter, but it seems that null values will not be sent to the converter
Solution
I'm using xStream 1.4 7. The @ xstreamalias annotation is used for custom field names, and the @ xstreamconverter is used for custom converters (used to represent dates and other custom beans) However, there is not even a custom converter that calls null values
I try to do this by creating a custom reflectionconverter I extended reflectionconverter from the xStream library and overridden the domarshal method The only thing I changed was null info Values calls the writefield method:
new Object() {
{
for (Iterator fieldIter = fields.iterator(); fieldIter.hasNext();) {
FieldInfo info = (FieldInfo) fieldIter.next();
if (info.value != null) {
//leave the code unchanged
...
} else {
//add this to write null info.value to xml
Log.info("MyCustomReflectionConverter -> serialize null field: " + info.fieldName);
writeField(info.fieldName,null,info.type,info.definedIn,info.value);
}
}
//... leave the rest of the code unchanged
}
};
After that, I created a similar xStream instance (it is important to register the converter with a very low priority):
StaxDriver driver = new StaxDriver(new NoNameCoder()) {
@Override
public StaxWriter createStaxWriter(XMLStreamWriter out) throws XMLStreamException {
// the boolean parameter controls the production of XML declaration
return createStaxWriter(out,false);
}
};
XStream xStream = new XStream(driver);
xStream.autodetectAnnotations(true);//needed to process aliases
//register MyCustomReflectionConverter
MyCustomReflectionConverter reflectionConverter = new MyCustomReflectionConverter (xStream.getMapper(),new SunUnsafeReflectionProvider());
xStream.registerConverter(reflectionConverter,XStream.PRIORITY_VERY_LOW);
Thanks for mark nabours' solution here
I hope I can help you Has anyone found a better solution?
