Re: JAXB unmarshalling - missing referenced objects
On 6 Apr, 16:42, n...@arenybakk.com wrote:
*snip*
Appearently I missed something not checking out the XmlJavaTypeAdapter-
annotation. In the Javadocs on the XmlAdapter-class I found this
sentence: "Some Java types do not map naturally to a XML
representation, for example HashMap or other non JavaBean classes". If
this could be the reasons for my problem, why did marshalling work
just fine? Am I on the right track here? :)
Yep, this did the trick! Collections of type Set, among other things,
doesn't work off the bat with JAXB. An adapter has to be made and it
is annotated with XmlJavaTypeAdapter.
//Removed: @XmlElementWrapper(name="elements", nillable=false)
@XmlElementRef
@XmlJavaTypeAdapter(value=ElementXmlAdapter.class)
@ManyToMany( //JPA
//...
)
public void getElements() {
//...
}
---ElementXmlAdapter---
public class ElementXmlAdapter extends
javax.xml.bind.annotation.adapters.XmlAdapter<ElementXmlContainer,Set<Element>>{
@Override
public Set<Element> unmarshal(ElementXmlContainer list) throws
Exception {
return new HashSet<Element>(list.getElements());
}
@Override
public ElementXmlContainer marshal(Set<Element> set) throws
Exception {
return new ElementXmlContainer(new ArrayList<Element>(set));
}
}
---ElementXmlContainer---
@XmlRootElement(name="elements")
public class ElementXmlContainer {
private List<Element> elements;
public ElementXmlContainer() {
}
public ElementXmlContainer(List<Element> elements) {
this.elements = elements;
}
@XmlElementRef
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
I have several Sets around in my classes so I thought I'd try to make
generic classes for the two above. This didn't work, though, and I
believe it has to do with the fact that with Generics the type is set
at run-time, meaning there's no way of saying
ElementXmlAdapter<Element>.class and ElementXmlAdapter.class != new
ElementXmlAdapter<Element>().class. As far as I can see anyway,
correct me if I'm wrong. If anyone has a solution to this, I'd really
appriciate it! :)