阅读:21962回复:0
map转换为对象
最近有人问当在后台接受前台的参数是一个包含了很多字段和数据的json,怎么把它转换为相应的对象,不使用传统的使用对象的set方法,而是使用反射来实现。下面是代码:
package mapToObject; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Test { public static void main(String[] args) throws ParseException { Map<Object, Object> data=new HashMap<Object, Object>(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); data.put("id", "123"); data.put("userName", "杨潇"); data.put("password", "123"); data.put("age", 18); data.put("birth", sdf.parse(sdf.format(new Date()))); System.out.println(data.toString()); Person p=new Person(); p=(Person) mapToObject(data,p); System.out.println(p.toString()); } public static Object mapToObject(Map<Object, Object> data,Object result){ //获取map对象的key Set keys=data.keySet(); Iterator iterator=keys.iterator(); while(iterator.hasNext()){ //对map进行遍历 Object key=iterator.next(); Object value=data.get(key); System.out.println(key+"="+value); if(key instanceof String){ String keyValue=(String)key; String methodName= "set"+keyValue.substring(0,1).toUpperCase()+keyValue.substring(1,keyValue.length()); //加载类 Class c=result.getClass(); //获取方法 try { //获取需要执行的set方法 Method method=c.getDeclaredMethod(methodName,value.getClass()); //执行方法 method.invoke(result,value); } catch (Exception e) { e.printStackTrace(); } } } return result; } } 下面是我的定义的一个javabean:Person.java package mapToObject; import java.util.Date; public class Person { private String id; private String userName; private String password; private Integer age; private Date birth; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "Person [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + ", birth=" + birth + "]"; } } 不懂得可以直接恢复问我。 |
|
|