Search code examples
javaserializationcollectionsnullxstream

xstream - unable to initialize values of custom list element


I have below Allocation & Charge beans with input XML as -

 public class Allocation {
     private Integer allocQty;
     private Double allocPrice;
     private List<Charge> charges;
 }
 public class Charge {
    private String chargeType;
    private String chargeSubType;
 }

<allocation>
    <allocQty />
    <allocPrice />
    <charges>
        <charge>
            <chargeType>A</chargeType>
            <chargeSubType>B</chargeSubType>
        </charge>
        <charge>
            <chargeType>C</chargeType>
            <chargeSubType>D</chargeSubType>
        </charge>
    </charges>
</allocation>

Trying with below xstream config gives me TWO elements list of Charge, but those Charge objects have all fields (String) as NULL !! Am I missing something here ?

XStream xstream = new XStream(new StaxDriver());
xstream.ignoreUnknownElements();

xstream.alias("allocation", Allocation.class);
...
xstream.alias("charge", Charge.class);
xstream.addImplicitCollection(Allocation.class, "charges", "charges", Charge.class);
...

Solution

  • By "implicit collection" XStream means collection of elements without enclosing ("root") element (see configuration manual). In your XML charge elements are enclosed by the charges element. Therefore charges is NOT implicit collection and addImplicitCollection configuration is wrong. So you can either leave XML as is and remove 'addImplicitCollection' invocation or remove charges element, like this:

    <allocation>
        <allocQty />
        <allocPrice />
        <charge>
            <chargeType>A</chargeType>
            <chargeSubType>B</chargeSubType>
        </charge>
        <charge>
            <chargeType>C</chargeType>
            <chargeSubType>D</chargeSubType>
        </charge>
    </allocation>
    

    (in the later case you also must fix typo: third parameter of addImplicitCollection must be "charge", not "charges").