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!
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) {}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.