1

Map がクラス内のオブジェクトとして渡され、Map のマーシャリング/アンマーシャリングに使用されるカスタム XMLJavaAdapter で注釈が付けられている多くの例を見てきました。しかし、私は 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 自体を入力要求エンティティとして渡したいのです。それを試してみると、ログに空の xml リクエストと 400 Bad Request が表示されます。

4

1 に答える 1