users@jaxb.java.net

Re: XmlJavaTypeAdapter help

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Mon, 25 Aug 2008 16:00:25 +0200

Perhaps I should have mentioned that you can marshal Map<K,V> "as is",
i.e., without any annotations or even adapters - provided that you are
satisfied with the XML structure and tags JAXB uses by default.

--->--- DocType.java
@XmlRootElement(name="doc")
public class DocType {

    public Map<KeyType,EntryType> key2entry =
        new HashMap<KeyType,EntryType>();

    public DocType(){
    }
}
---<---
--->--- KeyType.java
public class KeyType {
    public String major;
    public String minor;
    public KeyType(){}
    public KeyType( String maj, String min ){
        major = maj;
        minor = min;
    }
}
---<---
--->--- EntryType.java
import javax.xml.bind.annotation.*;

public class EntryType {
    public String str;
    public int num;

    public EntryType(){}
    public EntryType( String s, int i ){
        str = s;
        num = i;
    }
}
---<---

This marshals like this:
<doc>
    <key2entry>
        <entry>
            <key>
                <major>b</major>
                <minor>2</minor>
            </key>
            <value>
                <str>bbb</str>
                <num>222</num>
            </value>
        </entry>
        <entry>
            <key>
                <major>a</major>
                <minor>1</minor>
            </key>
            <value>
                <str>aaa</str>
                <num>111</num>
            </value>
        </entry>
    </key2entry>
</doc>


On Sun, Aug 24, 2008 at 6:34 PM, murakris <cme_mk_at_yahoo.com> wrote:
>
> Thanks for the explanation. It makes sense now. I also found that it is
> possible to achieve the same result (with course elements as direct children
> of brochure) by not using the XmlAdapter itself and instead annotating a
> getter method that returns a Course[] array (made of the map contents) like
> this:
>
>
> @XmlElement(name = "course")
> private Course[] getCourses() {
> Course[] result = new Course[courses.size()];
> int i = 0;
> for (String id : courses.keySet())
> result[i++] = courses.get(id);
>
> return result;
> }
>
> Regards,
> Murali