gpt4 book ai didi

java - 如何使用 Jersey 来编码和解码 map

转载 作者:行者123 更新时间:2023-12-01 04:38:44 25 4
gpt4 key购买 nike

我见过很多示例,其中 Map 作为类中的对象传递,并使用自定义 XMLJavaAdapter 进行注释,该自定义 XMLJavaAdapter 用于编码/解码 Map。但我试图将 Map 本身作为 POST 请求中的 requestEntity 传递,并将响应也作为 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 错误请求:

最佳答案

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

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

关于java - 如何使用 Jersey 来编码和解码 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16958194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com