简体   繁体   中英

java.util.Map in output of REST Service using jersey

I am using apache jersey 2.2 and I have the following rest service

@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 class 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;
}

}

and MapAdapter is defined as follows:

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;
}

}

the output of the rest service is

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

but I do not want the root element. My desidered output is the following:

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

What can I do to accomplish this goal ? Is it possible ?

many thanks

I solved using @XmlPath annotation.

In this way:

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

the map is serialized in the json itself without "map" reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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