欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

Java笔记-CXF使用Adapter处理复杂类型(如Map)

发布时间:2025/3/15 java 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Java笔记-CXF使用Adapter处理复杂类型(如Map) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

当有这个接口时:

Map<String, List<Role>>时报如下问题:

这里要使用Adapter进行处理:

接口换成:

@WebService public interface MyService {public String say(String str);@XmlJavaTypeAdapter(MapAdapter.class)public Map<String, List<Role>> getRoles(); }

实现为:

@WebService public class MyServiceImpl implements MyService {public String say(String str) {return "Hello" + str;}public Map<String, List<Role>> getRoles() {Map<String, List<Role>> map = new HashMap<String, List<Role>>();List<Role> roleList1 = new ArrayList<Role>();roleList1.add(new Role(1, "架构师"));roleList1.add(new Role(2, "技术总监"));map.put("xxx", roleList1);List<Role> roleList2 = new ArrayList<Role>();roleList2.add(new Role(3, "程序员"));map.put("yyy", roleList2);return map;} }

其中MapAdapter.java

public class MapAdapter extends XmlAdapter<MyRole[], Map<String, List<Role>>> {/**** 适配器转换 MyRole[] -> Map<String, List<Role>>* @param v* @return* @throws Exception*/public Map<String, List<Role>> unmarshal(MyRole[] v) throws Exception {Map<String, List<Role>> map = new HashMap<String, List<Role>>();for(int i = 0; i < v.length; i++){MyRole r = v[i];map.put(r.getKey(), r.getValue());}return map;}/**** 适配器转换 Map<String, List<Role>> -> MyRole[]* @param v* @return* @throws Exception*/public MyRole[] marshal(Map<String, List<Role>> v) throws Exception {MyRole[] roles = new MyRole[v.size()];int i = 0;for(String key : v.keySet()){roles[i] = new MyRole();roles[i].setKey(key);roles[i].setValue(v.get(key));}return roles;} }

MyRole.java

public class MyRole {private String key;private List<Role> value;public String getKey() {return key;}public void setKey(String key) {this.key = key;}public List<Role> getValue() {return value;}public void setValue(List<Role> value) {this.value = value;} }

Role.java

public class Role {private Integer id;private String roleName;public Role(){}public Role(Integer id, String roleName) {this.id = id;this.roleName = roleName;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;} }

User.java

public class User {private Integer id;private String userName;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;} }

源码打包下载地址为:

https://github.com/fengfanchen/Java/tree/master/CXFServiceAdapter

即可

 

 

总结

以上是生活随笔为你收集整理的Java笔记-CXF使用Adapter处理复杂类型(如Map)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。