1

My project uses XStream for serialization and must sometimes use the two-argument form of unmarshal that deserializes data into an existing root object.

Normally this works fine. The problem comes when an object initially has a non-null field value, and you are loading data which does not mention that field at all (perhaps because it was producing by marshaling a different object of the same class in which that field was null). After in-place unmarshaling, the field is still set. For example,

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XppDriver;
import java.io.StringReader;
import java.io.StringWriter;
public class Demo {
    static class Data {
        final String alpha;
        final String bravo;
        Data(String alpha, String bravo) {
            this.alpha = alpha;
            this.bravo = bravo;
        }
    }
    public static void main(String[] args) {
        Data d1 = new Data("one", "set");
        Data d2 = new Data("two", null);
        System.out.println(marshal(d1));
        System.out.println(marshal(d2));
        unmarshal(marshal(d2), d1);
        System.out.println(marshal(d1));
    }
    static XStream xs = new XStream();
    static XppDriver driver = new XppDriver();
    static String marshal(Object o) {
        StringWriter w = new StringWriter();
        xs.marshal(o, driver.createWriter(w));
        return w.toString();
    }
    static void unmarshal(String data, Object o) {
        xs.unmarshal(driver.createReader(new StringReader(data)), o);
    }
}

prints

<Demo_-Data>
  <alpha>one</alpha>
  <bravo>set</bravo>
</Demo_-Data>
<Demo_-Data>
  <alpha>two</alpha>
</Demo_-Data>
<Demo_-Data>
  <alpha>two</alpha>
  <bravo>set</bravo>
</Demo_-Data>

since d1.bravo is not cleared.

Is there a way to instruct the unmarshal method to unset all fields which are not explicitly mentioned in the input, so that in this case d1 would be made equal to d2?

Failing that, is there something that can be placed in the input specifically requesting a particular field to be unset? I tried both <bravo/> and <bravo><null/></bravo> without success—the bravo field is in both cases set to an empty string.

1 Answer 1

1

According to Jörg Schaible on the user list:

XStream always sets only the elements that are present in XML. The fields of uninitialized objects are always null. There is no code in XStream to uninitialize fields if you provide an existing object as root. The only alternative is currently a custom converter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.