gpt4 book ai didi

使用 jersey 的 REST 服务输出中的 java.util.Map

转载 作者:太空宇宙 更新时间:2023-11-04 13:18:43 25 4
gpt4 key购买 nike

我正在使用 apache jersey 2.2 并且我有以下休息服务

@GET
@Path("load3")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public LocalizationContainer load3() {
Map<String, String> map = new HashMap<String, String>();

map.put("key1", "value1");
map.put("key2", "value2");

return new SampleContainer(map);

}


@XmlRootElement

公共(public)类 SampleContainer{

public SampleContainer(){
}

public SampleContainer(Map<String,String> map){
this.map = map;
}

@XmlJavaTypeAdapter(value = MapAdapter.class)
private Map<String, String> map = new HashMap<String, String>();

public Map<String, String> getMap() {
return map;
}

public void setMap(Map<String, String> map) {
this.map = map;
}

}

MapAdapter定义如下:

public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, String>> {

public static class AdaptedMap {
@XmlVariableNode("key")
List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}

public static class AdaptedEntry {
@XmlTransient
public String key;
@XmlValue
public String value;
}

@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for (Entry<String, String> entry : map.entrySet()) {
AdaptedEntry adaptedEntry = new AdaptedEntry();
adaptedEntry.key = entry.getKey();
adaptedEntry.value = entry.getValue();
adaptedMap.entries.add(adaptedEntry);
}
return adaptedMap;
}

@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
List<AdaptedEntry> entries = adaptedMap.entries;
Map<String, String> map = new HashMap<String, String>(entries.size());
for (AdaptedEntry adaptedEntry : entries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}

}

其余服务的输出是

{"map":{"key2":"value2","key1":"value1"}}

但我不想要根元素。我想要的输出如下:

{"key2":"value2","key1":"value1"}

我可以做什么来实现这个目标?这可能吗?

非常感谢

最佳答案

我使用@XmlPath注释解决了。

这样:

@XmlJavaTypeAdapter(value = MapAdapter.class)
@XmlPath(".")
private Map<String, String> map = new HashMap<String, String>();

map 在 json 本身中序列化,没有“ map ”引用。

关于使用 jersey 的 REST 服务输出中的 java.util.Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307730/

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