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

标签 java rest 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

公共(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/

相关文章:

Java- Jersey ,JAX RS

java - 当我通过命令提示符运行我的 java 文件时出现错误

java - ANT build.xml 删除目录任务不起作用

rest - Github API 身份验证无法在拉取请求上添加评论

debugging - 如何调试 RESTful 服务?

python - Django REST - 如何获取具有两个模型的 JSON?

java - 在 android marshmallow (API v23) 上的 Cordova/phonegap 项目上添加运行时权限

java - 如何确保 LAN 故障立即导致 InterruptedException

java - 使用 Jersey JAX-RS 进行复杂的解编码(列表列表)

java - 设计 API 以使用 Jersey 启动和停止进程