Jersey 使用 JAXB 进行序列化。 JAXB 无法序列化 Map,因为 Java 类型 Map 没有 XML 类型。此外,Map 是一个接口,而 JAXB 不喜欢接口。
如果你使用 JAXBJackson 桥接器来编组,你会遇到问题。
您将需要创建一个如下所示的适配器并使用注释您的 Map 属性
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String,String> properties;
@XmlSeeAlso({ Adapter.class, MapElement.class })
public class MapAdapter<K,V> extends XmlAdapter<Adapter<K,V>, Map<K,V>>{
@Override
public Adapter<K,V> marshal(Map<K,V> map) throws Exception {
if ( map == null )
return null;
return new Adapter<K,V>(map);
}
@Override
public Map<K,V> unmarshal(Adapter<K,V> adapter) throws Exception {
throw new UnsupportedOperationException("Unmarshalling a list into a map is not supported");
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="Adapter", namespace="MapAdapter")
public static final class Adapter<K,V>{
List<MapElement<K,V>> item;
public Adapter(){}
public Adapter(Map<K,V> map){
item = new ArrayList<MapElement<K,V>>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
item.add(new MapElement<K,V>(entry));
}
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="MapElement", namespace="MapAdapter")
public static final class MapElement<K,V>{
@XmlAnyElement
private K key;
@XmlAnyElement
private V value;
public MapElement(){};
public MapElement(K key, V value){
this.key = key;
this.value = value;
}
public MapElement(Map.Entry<K, V> entry){
key = entry.getKey();
value = entry.getValue();
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}