2013-06-06 58 views
1

我已經看到很多示例,其中Map以類中的對象的形式傳遞,並使用用於編組/解組映射的自定義XMLJavaAdapter進行了註釋。但我試圖在POST請求中將映射本身作爲requestedEntity傳遞,並且響應也作爲Map而不是包含Map的類,因爲我可以看到衆多解決方案。如何使用Jersey對編組地圖進行解組編組

Input Class(Requested Entity): GenericMap.java

import java.util.HashMap; 
import javax.xml.bind.annotation.XmlRootElement; 

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; 

@XmlRootElement 
@XmlJavaTypeAdapter(GenericMapAdapter.class) 
public class GenericMap<K,V> extends HashMap<K,V> { 

} 

GenericMapAdapter.java

import java.util.HashMap; 
import java.util.Map; 
import java.util.Map.Entry; 

import javax.xml.bind.annotation.adapters.XmlAdapter; 


public class GenericMapAdapter<K, V> extends XmlAdapter<MapType<K,V>, Map<K,V>> { 

    @Override 
    public MapType marshal(Map<K,V> map) throws Exception { 
     MapType<K,V> mapElements = new MapType<K,V>();   

     for (Map.Entry<K, V> entry : map.entrySet()){ 
      MapElementsType<K,V> mapEle = new MapElementsType<K,V>  (entry.getKey(),entry.getValue()); 
      mapElements.getEntry().add(mapEle); 
     } 
     return mapElements; 
    } 

    @Override 
    public Map<K, V> unmarshal(MapType<K,V> arg0) throws Exception { 
     Map<K, V> r = new HashMap<K, V>(); 
     K key; 
     V value; 
     for (MapElementsType<K,V> mapelement : arg0.getEntry()){ 
      key =mapelement.key; 
      value = mapelement.value; 
      r.put(key, value); 
     } 
     return r; 

    } 
} 

MapType.java

import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 

import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class MapType<K, V> { 

    private List<MapElementsType<K, V>> entry = new ArrayList<MapElementsType<K, V>>(); 

    public MapType() { 
    } 

    public MapType(Map<K, V> map) { 
     for (Map.Entry<K, V> e : map.entrySet()) { 
      entry.add(new MapElementsType<K, V>(e.getKey(),e.getValue())); 
     } 
    } 

    public List<MapElementsType<K, V>> getEntry() { 
     return entry; 
    } 

    public void setEntry(List<MapElementsType<K, V>> entry) { 
     this.entry = entry; 
    } 
} 

MapElementsType.java

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 


@XmlRootElement 
public class MapElementsType<K,V> 
{ 
    @XmlElement public K key; 
    @XmlElement public V value; 

    public MapElementsType() {} //Required by JAXB 

    public MapElementsType(K key, V value) 
    { 
    this.key = key; 
    this.value = value; 
    } 

} 

當我做genericmap作爲類的成員變量,並與GenericMapAdapter註釋它,它工作正常。但是,我希望GenericMap本身作爲輸入請求實體傳遞。當我嘗試,我看到在我的日誌空的XML請求和400錯誤的請求:

回答