java对象转变为map
直接上代码
package com.**.**.**.common; import com.**.**.**.util.JsonUtils; import org.springframework.beans.BeanUtils; import org.springframework.util.ReflectionUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ClassUtils { public static void main(String[] args) { User u = new User(1L, "zyydd", "北京", "110"); System.out.println(JsonUtils.toJSONString(u)); Map<String, Object> map = parseObj2Map(u); System.out.println(JsonUtils.toJSONString(map)); } public static Map<String, Object> parseObj2Map(Object args) { return Arrays.stream(BeanUtils.getPropertyDescriptors(args.getClass())) .filter(pd -> !"class".equals(pd.getName())) .collect(HashMap::new, (map, pd) -> map.put(pd.getName(), ReflectionUtils.invokeMethod(pd.getReadMethod(), args)), HashMap::putAll); } public static class User { Long id; String name; String addr; String mobile; User(Long id, String name, String addr, String mobile) { this.id = id; this.name = name; this.addr = addr; this.mobile = mobile; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } } }
执行结果