繁体   English   中英

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

[英]java.util.Map in output of REST Service using jersey

我正在使用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"}

我该怎么做才能实现这个目标? 可能吗 ?

非常感谢

我使用@XmlPath注释解决了。

通过这种方式:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM