您的位置:首页 > 其它

Hello Mr.J——WebService传递Map类型

2016-06-30 19:21 423 查看
  上篇博客提到了,WebService不能传递Map类型的数据,然而我还是找到了一种方法可以传过去,用的就是JDK自带的适配器。

  比如,上篇博客中,我的代码出现了这样一段。

@WebMethod
@XmlJavaTypeAdapter(MapAdapter.class)
@WebResult(partName = "return")
Map<String, Object> queryProfessionalByCollageId(
@WebParam(name = "collageId") String collageId, @WebParam(name = "dataBaseName") String dataBaseName, @WebParam(name = "name") String name);
  这个就是使用了XmlJavaTypeAdapter这个注解,注解中写的类是我们自己对这个Map进行处理的类。

public class MapAdapter extends XmlAdapter<MapConvertor, Map<String, Object>> {

@Override
public MapConvertor marshal(Map<String, Object> map) throws Exception {
MapConvertor convertor = new MapConvertor();
for (Map.Entry<String, Object> entry : map.entrySet()) {
MapConvertor.MapEntry e = new MapConvertor.MapEntry(entry);
convertor.addEntry(e);
}
return convertor;
}

@Override
public Map<String, Object> unmarshal(MapConvertor map) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
for (MapConvertor.MapEntry e : map.getEntries()) {
result.put(e.getKey(), e.getValue());
}
return result;
}
}
  还有一个转换之后的实体类。

@XmlType(name = "MapConvertor")
@XmlAccessorType(XmlAccessType.FIELD)
public class MapConvertor {
private List<MapEntry> entries = new ArrayList<MapEntry>();

public void addEntry(MapEntry entry) {
entries.add(entry);
}

public void setEntries(List<MapEntry> entries) {
this.entries = entries;
}

public List<MapEntry> getEntries() {
return entries;
}

public static class MapEntry {

private String key;

private Object value;

public MapEntry() {
super();
}

public MapEntry(Map.Entry<String, Object> entry) {
super();
this.key = entry.getKey();
this.value = entry.getValue();
}

public MapEntry(String key, Object value) {
super();
this.key = key;
this.value = value;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public Object getValue() {
return value;
}

public void setValue(Object value) {
this.value = value;
}
}
}
  然后我们在客户端调用的时候会返回一个MapConventor类型的对象,这个时候我们直接使用 getEntries()方法,可以获得一个list.

  对这个list进行处理循环放到map里面就能和应该返回的结果一样了,下篇搞客户端的时候补代码- -。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: