Map-JSON-对象 三者转换

Map-JSON-对象 三者转换

Map转对象

方法一:使用BeanUtils工具类

org.apache.commons.beanutils.BeanUtils的populate方法

方法
BeanUtils对象populate(Object bean, Map<String,String[]>properties)将Map数据封装到指定Javabean中,一般用于将表单的所有数据封装到javabean
setProperty(Object obj,String name,Object value)设置属性值
getProperty(Object obj,String name)获得属性值

示例:
在这里插入图片描述

方法二:反射

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mes.common.core.utils.StringUtils;
 
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public static Object convertToObject(Class clazz, Map<String, Object> map) throws
            IntrospectionException, InstantiationException, IllegalAccessException {
        BeanInfo bi = Introspector.getBeanInfo(clazz);
 
        Object obj = clazz.newInstance();
 
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();
 
        String pName;
        for (PropertyDescriptor pd : pds) {
            pName = pd.getName();
            if (map.containsKey(pName)) {
                try {
                    if (pd.getPropertyType().getName().equals("java.lang.Long")) {
                        if(StringUtils.isNotEmpty(map.get(pName).toString())){
                            pd.getWriteMethod().invoke(obj, Long.parseLong(map.get(pName).toString()));
                        }
//                        else{
//                            pd.getWriteMethod().invoke(obj, map.get(pName));
//                        }
                    } else {
                        pd.getWriteMethod().invoke(obj, map.get(pName));
                    }
                } catch (Exception ex) {
                    Logger.getLogger(MapUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
 
     return obj;
}

方法三:自写工具类

public static void copyMapToObject(Map<String, String> map, Object o) {
        Set<String> set = map.keySet();
        Class c = o.getClass();
        Field[] fields = c.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            if (set.contains(f.getName())){
                try {
                    f.set(o, map.get(f.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Map转JSON

Map转json字符串

方法一:导入阿里巴巴fastjson依赖包:
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.24</version>
</dependency>

Map map=new HashMap();
map.put("page_size","10");
map.put("page_index","1");
String  param= JSON.toJSONString(map);
方法二:遍历map取值转换
    public static String mapToJsonString(Map map) {
        JSONObject json = new JSONObject();
        Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            json.put(entry.getKey(), entry.getValue());
        }
        return json.toString();
    }

Map转json数组

导入阿里巴巴fastjson依赖包:
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.24</version>
</dependency>

Map map=new HashMap();
map.put("page_size","10");
map.put("page_index","1");
JSONArray jArray = new JSONArray(); 
jArray.add(map);
String str = jArray.toString();

对象转Map

    public static Map<String, String> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
 
        Map<String, String> map = new HashMap<String, String>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (key.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method getter = property.getReadMethod();
                Object value = getter != null ? getter.invoke(obj) : null;
                String v = null;
                if (value != null) {
                    v = value.toString();
                }
                map.put(key, v);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
 
    public static Map<String, Object> objectToMapObj(Object obj) {
        if (obj == null) {
            return null;
        }
 
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (key.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method getter = property.getReadMethod();
                Object value = getter != null ? getter.invoke(obj) : null;
                map.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

JSON转Map

JSON字符串转Map

    public static Map<String, Long> jsonStringToMap(String str) {
        Map<String, Long> map = (Map<String, Long>) JSON.parse(str);
        return map;
    }

JSON字符串转JSONObject

private JSONObject StringToJSONObject(String requestData) {
        try{
            JSONObject jsonObject = new JSONObject(requestData);
            return jsonObject;
        }catch (Exception e){
            //说明字符串不是JSON格式数据
            return null;
        }
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值