XStream serialize null values

前端 未结 3 480
再見小時候
再見小時候 2021-01-18 05:38

Suppose I have

class Student
{
String name;
int    age;
String teacher;
}

Then :

public class App1
{
    public static voi         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-18 06:14

    I'm using XStream 1.4.7, @XStreamAlias annotation for custom field names, @XStreamConverter for custom converters (to represent dates and other custom beans). However, a custom converter for null values was not even called. My goal was to serialize all the fields of the object, including the null ones, I didn't need to unmarshal XML.

    I managed to do that by creating a custom ReflectionConverter. I extended ReflectionConverter from XStream library and overrode doMarshal method. The only thing I changed was calling 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 xStream instance like that (it is very important to register your converter with 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 it helps. Has anyone found a better solution for this?

提交回复
热议问题