如何使用Jersey解组地图解组

时间:2013-06-06 09:16:25

标签: java json jersey marshalling unmarshalling

我见过很多例子,其中Map作为对象传递到类中,并使用自定义XMLJavaAdapter进行注释,该自定义XMLJavaAdapter用于编组/解组Map。但是我试图将一个Map本身作为POST请求中的requestedEntity传递,并且响应也作为Map而不是包含Map的类,我可以看到很多解决方案..

输入类(请求实体): 的 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本身作为输入请求实体传递。当我尝试这个时,我在我的日志和400 Bad Request中看到一个空的xml请求:

1 个答案:

答案 0 :(得分:0)

我认为您的问题的解决方案是不使用JAXB并对请求参数或响应进行手动映射:

请参阅In Jersey, how do I make some methods use the POJO mapping feature and some not?

相关问题