简体   繁体   中英

jaxb unmarshaling a list of derived objects

I'm trying to unmarshal a list of objects that derive from a common base class. They are defined as this:

public abstract class Par {
  @XmlTransient
  public String name;

  @XmlAttribute(name="name")
  public String getName() {
    return name;
  }

  public void setName(String n) {
    name = n;
  }
}

@XmlRootElement(name="int")
public class IntegerPar extends Par {
    @XmlTransient
    public int value;

    @XmlAttribute(name="value")
    public int getValue() {
      return value;
    }

    public void setValue(int v) {
      value = v;
    }
}

@XmlRootElement(name="string")
public class StringPar extends Par { ... }

Now, if I create a List and marshal it to xml, it works as expected producing a neat

<root>
  <int name="x" value="1"/>
  <string name="s" value="hello"/>
</root>

but if I want to unmarshal that same xml into this class

@XmlRootElement(name="root")
public class ParamRequest {
  @XmlAnyElement
  public ArrayList<Par> params;
}

I get the following (taken from eclipse debug)

myRequest.params    [[int: null], [string: null]]

Any help? Thanks.

EDIT: The unmarshaling is done by Jersey

@POST @Path("/params")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_XML)
public String postParams(ParamRequest myRequest) {
    myRequest...
    ...
}

Use @XmlSeeAlso to let know the JAXB about the subclass during marshall/unmarshall.

@XmlSeeAlso({IntegerPar.class,StringPar.class})
public abstract class Par {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM