1

I have problem with mapping map of my objects to xml via JAXB. To get prety xml from marshaller I use @XmlJavaTypeAdapter which map Map.Entry to my class which has jaxb annotation to create nice xml, but the problem is that value in my wrapper class is only the reference to the real object and while unmarshalling in time when adapter is called there is null in this value(the object is specified later in xml) and at the end of unmarshalling when jaxb try to resolve this references the objects are put into my wrapper objects, not into my map.

For better understand here is a sample xml:

<root>
    <map>
        <wrapper key="k1" value="n1" />
        <wrapper key="k2" value="n2" />
        <wrapper key="k3" value="n3" />
        <wrapper key="k4" value="n4" />
    </map>
    <list>
        <A name="n1" param="aaa" />
        <A name="n2" param="bbb" />
        <A name="n3" param="ccc" />
        <A name="n4" param="ddd" />
    </list>
</root>

And java classes(it's only a sample for better understanding the problem):

@XmlRootElement(name="root")
class Root {
    @XmlElement(name = "map")
    @XmlJavaTypeAdapter(MyAdapter.class)
    public Map<String, A> map = new HashMap();

    @XmlElementWrapper(name = "list")
    @XmlElement(name = "A")
    public List<A> list = new ArrayList();
}

class A {
    @XmlID
    @XmlAttribute
    public String name;
    @XmlAttribute
    public String param;
}

class MyAdapter extends XmlAdapter<MapWrapper, Map<String, A>> {
    @Override
    public Map<String, A> unmarshal(MapWrapper v) throws Exception {
        Map<String, A> map = new HashMap()
        for(EntryWrapper e : v.value) {
            map.put(e.key, e.value);
        }
        return map;
    }

    @Override
    public MapWrapper marshal(Map<String, A> v) throws Exception {
        MapWrapper mw = new MapWrapper();
        for(Map.Entry<String, A> entry : v.getEntrySet()) {
            mv.value.add(new EntryWrapper(entry.getKey(), entry.getValue();
        }
        return mw;
    }
}

class MapWrapper {
    @XmlElement(name = "wrapper")
    public List<EntryWrapper> value = new ArrayList();
}

class EntryWrapper {
    @XmlAttribute
    public String key;
    @XmlAttribute
    @XmlIDREF
    public A value;

    public EntryWrapper(String key, A value) {
        this.key = key;
        this.value = value;
    }
}

And after unmarshalling I have null values in map.

gandalfml
  • 908
  • 1
  • 10
  • 23

0 Answers0