2012-08-01 40 views
0

我有這個結構的XML(項鍵值對)解組的哈希地圖: 使用JAXB從列表

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

我想要的項目元素,以一個HashMap映射,該字符串Item.key

我寫了一個適配器,它將xml中的列表解組並將marshals映射到列表。 問題是,解組時,JAXB獲取列表emtpy並且只編寫一個項目時編組到xml。

下面是相應的類:

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){} 
} 

任何人有任何見解? 可能是缺少的東西.. 謝謝!

回答

0

你應該在你的適配器切換HashMapLinkedList

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) {} 
} 
+0

另外的我想已經:\如果我轉的是,我不能在根對象在Java中,這是地圖基本上是我想要的。 – Cu7l4ss 2012-08-01 14:02:48

+0

檢查答案:http://stackoverflow.com/a/4597301/1384984 – tibtof 2012-08-01 14:08:22