I am using XStream 1.4.7, the annotation @XStreamAlias ββfor custom field names, @XStreamConverter for custom converters (to represent dates and other custom beans). However, a custom converter for zero values ββwas not even called. My goal was to serialize all fields of an object, including null, I did not need to untie XML.
I managed to do this by creating a custom ReflectionConverter. I extended the ReflectionConverter from the XStream library and tried the doMarshal method. The only thing I changed is the call to the writeField method for null info.values:
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 such an instance of xStream (it is very important to register your 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 to Mark Nabours for his solution here.
Hope this helps. Has anyone found a better solution for this?
Popstore
source share