FastJson 把对象转化为Map

FastJson 把对象转化为Map

1.项目引入依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
 <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.56</version>
</dependency>

2.使用FastJson的ParseObject 方法
//导包

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

/**

 * 
 * @MethodName: getUserInfoDataByUserId
 * @Description: 根据useId查询用户信息,封装成map  key:属性名,value:属性值
 * home.php?mod=space&uid=952169 userId 用户userId
 * @return
 */
public Map<String, String> getUserInfoDataByUserId(String userId) {
    Map<String, String> userMap = new HashMap<String, String>();
    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<Map<String, String>>() {
            });
        }
    }
    return userMap;
}

3.提供接口,供其他模块调用

/**
     * 
     * @MethodName: getAppDataBySceneId
     * @Description: 根据userid获取用户信息
     * @param userId 用户userId
     * @param type 用户对象的属性名,例如 userName,trueName,mobile,userSex,photo
     * @return
     */
    @ResponseBody
    @RequestMapping("/api/user/getUserSingleInfoByUserIdAndAttribute")
    public ResponseData getUserSingleInfoByUserIdAndAttribute(String userId, String type) {
        ResponseData data = operateFailed("获取数据失败");
        String message = "用户信息获取成功";
        if (StringUtils.isBlank(userId)) {
            data = operateFailed("userId 为空!");
            return data;
        }
        if (StringUtils.isBlank(type)) {
            data = operateFailed("type 属性名为空,例如userName,trueName,photo!");
            return data;
        }

        Map<String, String> userMap = getUserInfoDataByUserId(userId);
        String value = "";
        if (null != userMap && StringUtils.isNoneBlank(type)) {
            switch (type) {
            case "userName":
                value = userMap.get("userName");
                break;
            case "trueName":
                value = userMap.get("trueName");
                break;
            case "photo":
                value = userMap.get("photo");
                break;
            case "mobile":
                value = userMap.get("mobile");
                break;
            case "isDel":
                value = userMap.get("isDel");
                break;
            case "userSex":
                value = userMap.get("userSex");
            case "createTime":
                value = userMap.get("createTime");
                break;
            }
        }
        if (StringUtils.isNoneBlank(value)) {
            data = operateSucess(message, value);
        }
        return data;
    }

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

public class BeanMapUtilByReflect {

    /**
     * 对象转Map
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map beanToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        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> T mapToBean(Map map, Class<T> 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;
    }
}

方式三: 利用工具类进行转换

/**
     * 
     * @MethodName: getUserInfoDataByUserId
     * @Description: 根据useId查询用户信息,封装成map  key:属性名,value:属性值
     * @param userId 用户userId
     * @return
     */
    public Map<String, String> getUserInfoDataByUserId(String userId) {
        Map<String, String> userMap = new HashMap<String, String>();
        BSysUser bSysUser = new BSysUser();
        if (StringUtils.isNoneBlank(userId)) {
            bSysUser = bSysUserService.selectByKey(userId);
            if (null != bSysUser) {
                //import org.apache.commons.beanutils.BeanMap;
                //userMap = new BeanMap(bSysUser);

                //import org.apache.commons.beanutils.BeanUtils;
                //userMap = BeanUtils.describe(user);

                //效果等同
                userMap = JSON.parseObject(JSON.toJSONString(bSysUser), new TypeReference<Map<String, String>>() {
                });
            }
        }
        return userMap;
    }

        //import org.apache.commons.beanutils.BeanMap;
        //userMap = new BeanMap(bSysUser);
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

你可能感兴趣的:(java)