将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);