users@jaxb.java.net

XmlAdapter and array types?

From: thomas weidner <3.14159_at_gmx.net>
Date: Mon, 19 Jun 2006 01:34:26 +0200

Hi,

i'm running into serious problems when using XmlAdapter with array types
as ValueType. I could try to explain a lot,but i'll post my sample code:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "ys"
})
@XmlRootElement(name = "main")
public class Main {

    @XmlElement(required = true,name="y")
    @XmlJavaTypeAdapter(value=Adapter.class)
    protected Map<String,Foo> ys;

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "foo", propOrder = {
    "x",
    "y"
})
public class Foo {

    @XmlElement(required = true)
    protected String x;
    @XmlElement(required = true)
    protected String y;
}

public class Adapter extends XmlAdapter<Foo[],Map<String,Foo>> {

    @Override
    public Map<String, Foo> unmarshal(Foo[] arg0) throws Exception {
        Map<String,Foo> r=new HashMap<String,Foo>();
        for(Foo f:arg0)
            r.put(f.x,f);
        return r;
    }

    @Override
    public Foo[] marshal(Map<String, Foo> arg0) throws Exception {
        return arg0.values().toArray(new Foo[arg0.size()]);
    }
   
}

public class Tester {
   
    public static void main(String[] args) throws Exception {
        JAXBContext context =
JAXBContext.newInstance("de.uni_leipzig.swtp.tr06_2.wiki.test");
        Unmarshaller um = context.createUnmarshaller();
        Main main = (Main)um.unmarshal(new
File("/home/thomas/swtp/LilaWiki/etc/test.xml"));
        System.out.println(main.ys.size());
    }

}

and the sample input is:
<?xml version="1.0" encoding="UTF-8"?>
<main xmlns="http://www.example.org/test"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/test test.xsd ">
    <y>
        <x>x</x>
        <y>y</y>
    </y>
    <y>
        <x>1</x>
        <y>2</y>
    </y>
</main>

and this is what happens:
0

i really don't know what i did wrong,why my Map is empty. i debugged it
and recognized that the Adapter's method actually is called,but with a
Foo[0] argument. I searched the web and found kohsuke's tutorial on how
to write adapters,i think i did nearly the same as he did. finally when
leaving out the @XmlJavaTypeAdapter and using a List instead of a Map i
get the correct output of '2'. tested with jaxb 2.0.1. what did i wrong?
or is it a bug?

    thanks in advance Thomas