Reputation: 1952
I would like to unmarshall XML using JAXB unmarshaller to the object of this type.
public class Pair<T1,T2> implements Serializable {
private T1 first;
private T2 second;
public Pair(T1 first, T2 second) {
this.first = first;
this.second = second;
}
public T1 getFirst() {
return first;
}
public void setFirst(T1 first) {
this.first = first;
}
public T2 getSecond() {
return second;
}
public void setSecond(T2 second) {
this.second = second;
}
}
public class TripPair<T1,T2> extends Pair<T1,T2> {
public TripPair(T1 first, T2 second) {
super(first, second);
}
}
public class Fare extends Pricing implements Comparable<Fare> {
private List<TripPair<Integer,Integer>> trips = new LinkedList<>();
}
XML file
<fareGroups>
<trips>
<second>37</second>
<first>0</first>
</trips>
</fareGroups>
XML file have also other data and it is unmarshalled, unfortunately data from elements first
and second
are not unmarshalled. I tried to add @XmlElement
annotations on these fields to Pair
class, but without sucesss.
Using XmlAdapter
public class PairAdapter extends XmlAdapter<String, Integer> {
public String marshal(Integer val) throws Exception {
return val.toString();
}
public Integer unmarshal(String val) throws Exception {
return Integer.valueOf(val);
}
}
public class Pair<T1,T2> implements Serializable {
@XmlJavaTypeAdapter(PairAdapter.class)
private T1 first;
@XmlJavaTypeAdapter(PairAdapter.class)
private T2 second;
}
Upvotes: 2
Views: 97
Reputation: 148977
You will need to add a zero-arg constructor, or create an XmlAdapter
for the Pair
class to get it to unmarshal correctly (see: http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html).
I'm using JAXB marshaller for it and when I made a debugging of non-marshalled element, it has wrong type. ElementNSImpl instead of Integer.
As far as JAXB is concerned first
and second
will be treated as type Object
, since it derives metadata at the class level Pair
instenad of the type level Pair<Integer, Integer>
. Because of this the XML will need to qualify the XML elements with the necessary type information. This is done using the xsi:type
attribute.
public class Pair<T1,T2> implements Serializable {
private T1 first;
private T2 second;
Try populating your object model with the data you want and then marshalling it and you will see what the XML should look like for the unmarshal operation.
Upvotes: 3