0

I have an xml of this structure (Key value pairs of items):

<root>
  <item value="dada" key="dad" />
  <item value="mama" key="mum" />
  <others>
    <os>asdad</os>
  </others>
</root>

I want to map the item elements to a HashMap, the string is Item.key

I wrote an adapter that unmarshals a list from the xml and marshals a map to a list. Problem is, JAXB gets the list emtpy when unmarshal-ing and only writes one item when marshal-ing to xml.

Here are the corresponding classes:

Root.java

@XmlRootElement(name = "root")
public class Root
{
    @XmlJavaTypeAdapter(ItemMapAdapter.class)
    @XmlElement(name = "item")
    public HashMap<String, Item> getContent()
    {
        return content;
    }

    public void setContent(HashMap<String, Item> content)
    {
        this.content = content;
    }

    private HashMap<String, Item> content;
}

ItemMapAdapter.java

public final class ItemMapAdapter extends XmlAdapter<HashMap<String, Item>, LinkedList<Item>>
{
    @Override
    public HashMap<String, Item> marshal(LinkedList<Item> v)
    {
         //the list here is empty.
         //returns a map<Item.key, Item>
    }

    @Override
    public LinkedList<Item> unmarshal(HashMap<String, Item> v){}
}

Anyone has any insights? probably am missing something.. Thanks!

Cu7l4ss
  • 556
  • 1
  • 8
  • 19

1 Answers1

0

You should switch HashMap and LinkedList in your adapter:

public final class ItemMapAdapter extends XmlAdapter<LinkedList<Item>, HashMap<String, Item>>
{
    @Override
    public LinkedList<Item> marshal(HashMap<String, Item> v) {}

    @Override
    public HashMap<String, Item> unmarshal(LinkedList<Item> v) {}
}
tibtof
  • 7,857
  • 1
  • 32
  • 49
  • Besides of me trying that already :\ if I switch that, I can't get the map in the root object in java, which is essentially what I want. – Cu7l4ss Aug 01 '12 at 14:02