我正在使用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
公共类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"}
我可以做些什么来实现这个目标? 有可能吗?
非常感谢答案 0 :(得分:0)
我使用@XmlPath注释解决了。
这样:
@XmlJavaTypeAdapter(value = MapAdapter.class)
@XmlPath(".")
private Map<String, String> map = new HashMap<String, String>();
地图在json本身序列化,没有“地图”参考。