2011-08-02 43 views
2

我想讓XmlAdapter工作到一個HashMap並且我不斷收到異常。我非常密切關注this blog entry,並且我已經結束了很多次我的代碼,但我沒有看到問題。無法讓簡單的XmlAdapter工作

我正在使用最新版本的org.eclipse.persistence.jaxb.JAXBContextFactory作爲我的JAXB提供程序。

這裏是我的XML的一個樣本:

<test> 
    <myName>Paul</myName> 
    <mappings> 
    <entry key="man">manufacturer</entry> 
    <entry key="prod">product</entry> 
    </mappings> 
<test> 

按照上面提到的博客文章中的步驟:

1.確定不可映射類

我想地圖a java.util.HashMap

2.創建一個等價類是可映射

public class MappingType 
{ 
    public List<MappingEntryType> entry = new ArrayList<MappingEntryType>(); 
} 

public class MappingEntryType 
{ 
    @XmlAttribute 
    public String key; 
    @XmlValue 
    public String value; 
} 

3.創建XmlAdapter到不可映射和可映射之間轉換對象

public class MappingAdapter extends XmlAdapter<MappingType, 
               HashMap<String, String>> 
{ 
    @Override 
    public HashMap<String, String> unmarshal(MappingType v> throws Exception 
    { 
    HashMap<String, String> hashMap = new HashMap<String, String>(); 
    for (MappingTypeEntry mappingEntry : v.entry) 
    { 
     hashMap.put(mappingEntry.key, mappingEntry.value); 
    } 
    return hashMap; 
    } 

    // marshal is here but I'm just working on unmarshalling now 
} 

4.指定XmlAdapter

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name = "test") 
public class TestEntity 
{ 
    @XmlElement 
    private String myName; 

    @XmlJavaTypeAdapter(MappingAdapter.class) 
    HashMap<String, String> mappings; 

    // getters & setters omitted in a feeble attempt at brevity 
} 

我已經加入下一步,我稱之爲 5.堆棧跟蹤

Exception [EclipseLink-3001](Eclipse Persistence Services-2.3.0.v20110604-r9504): 
org.eclipse.persistence.exceptions.ConversionException 
ExceptionDescription: The object [[email protected]], of class 
[class mypackage.MappingType],could not be converted to [class java.util.HashMap] 
    at etc etc 

的異常說明是很清楚,但我看不到的地方我想一個MappingType轉換爲HashMap。有時候輸入一個問題會讓我回答這個問題,但這次不是。

我確定這很簡單 - 如果你看到我的錯誤,請指出!

謝謝!

順便說一句,Blaise Doughan's blog充滿了很棒的JAXB和MOXY信息,值得一看。

回答

1

我想如何解決這個問題,即使我不明白髮生了什麼事情。

我在此項目中使用Spring框架,我的XmlAdapter類標記爲@Component。刪除該註釋使代碼完美工作。出於某種原因,由Spring管理的適配器阻止了我的JAXB提供者使用該類解組我的XML。

0

你可以參考XmlAdapter的officail documentatio。他們舉了同樣的例子。