菜鸟笔记
提升您的技术认知

java 对象转化为map-ag真人游戏

方式一: 利用fastjson 把对象转化为map

/**
     * 
     * @methodname: getuserinfodatabyuserid
     * @description: 根据useid查询用户信息,封装成map  key:属性名,value:属性值
     * home.php?mod=space&uid=952169 userid 用户userid
     * @return
     */
    public map getuserinfodatabyuserid(string userid) {
  
        map usermap = new hashmap();
        bsysuser bsysuser = new bsysuser();
        if (stringutils.isnoneblank(userid)) {
  
            bsysuser = bsysuserservice.selectbykey(userid);
            if (null != bsysuser) {
  
                //usermap = new beanmap(bsysuser);
                usermap = json.parseobject(json.tojsonstring(bsysuser), new typereference>() {
  
                });
            }
        }
        return usermap;
    }

方式二: 利用反射进行转换

public class beanmaputilbyreflect {
  
    /**
     * 对象转map
     * @param object
     * @return
     * @throws illegalaccessexception
     */
    public static map beantomap(object object) throws illegalaccessexception {
  
        map map = new hashmap();
        field[] fields = object.getclass().getdeclaredfields();
        for (field field : fields) {
  
            field.setaccessible(true);
            map.put(field.getname(), field.get(object));
        }
        return map;
    }
    /**
     * map转对象
     * @param map
     * @param beanclass
     * @param 
     * @return
     * @throws exception
     */
    public static  t maptobean(map map, class beanclass) throws exception {
  
        t object = beanclass.newinstance();
        field[] fields = object.getclass().getdeclaredfields();
        for (field field : fields) {
  
            int mod = field.getmodifiers();
            if (modifier.isstatic(mod) || modifier.isfinal(mod)) {
  
                continue;
            }
            field.setaccessible(true);
            if (map.containskey(field.getname())) {
  
                field.set(object, map.get(field.getname()));
            }
        }
        return object;
    }
}
网站地图