将map映射成实体

将map映射成实体

一、利用插件

1.hfxy_merchant 为实体类 bean

2.Map<String,Object> paramMap

3.导入的包

  import com.alibaba.fastjson.JSON;
  import com.alibaba.fastjson.JSONArray;
  import com.alibaba.fastjson.JSONObject;
  import com.google.gson.Gson;
  import com.google.gson.JsonObject;

hfxy_merchant merchant = new Gson().fromJson(new JSONObject(paramMap).toJSONString(),hfxy_merchant.class);

二、利用反射

需要注意的是:利用反射的方式来做,需要注意的是javaBean参数的类型需要是封装类int->Integer boolean->Boolean

1.实体类

public class hfxy_merchant {
public Integer merchant_id;
public String merchant_num;
public String merchant_name;
public Boolean is_use;

   }

2.java 类

      /**
* 将Map转成javaBean对象
* @param map
* @param beanClass
* @return
* @throws Exception
*/
public static Object mapToObject(Map<String, Object> map, Class<?> hfxy_merchant) throws Exception {    
        if (map == null)  
            return null;    
  
        Object obj = hfxy_merchant.newInstance();  
  
        java.lang.reflect.Field[] fields = obj.getClass().getDeclaredFields();   
        for (java.lang.reflect.Field field : fields) {    
            int mod = field.getModifiers();    
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){    
                continue;    
            }    
  
            field.setAccessible(true);    
            field.set(obj, map.get(field.getName()));   
        }   
  
        return obj;    
    }

3.测试函数main方法

public static void main(String[] args) {
	Map<String,String> param1 = new HashMap<String, String>();
	param1.put("merchant_id", "1234");
	param1.put("merchant_num", "4561");
	param1.put("merchant_name", "你猜");
	param.put("is_use", 1);
	Map<String,Object> param = new HashMap<String, Object>();
	param.putAll(param1);
	hfxy_merchant mer = new hfxy_merchant();
	try {
		mer = (hfxy_merchant) mapToObject(param,mer.getClass());
		System.out.println(mer);
	} catch (Exception e) {
		e.printStackTrace();
	}
	System.out.println(mer.merchant_num);
}

将list映射成实体

一、利用插件

1.导包

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

2.方法

List list = new ArrayList();
hfxy_merchant mer2 = new Gson().fromJson(new JSONArray(list).toJSONString(), hfxy_merchant.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值