Java如何实现实体类转Map、Map转实体类

时间:2022-09-10 13:30:49

实体类转Map、Map转实体类

1、创建entity(User.java)

package com.jeff.entity;
public class User {
 private String userName;
 private String password;
 private Integer age;
 public User() {
  super();
 }
 public User(String userName, String password, Integer age) {
  super();
  this.userName = userName;
  this.password = password;
  this.age = age;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return "User [userName=" + userName + ", password=" + password + ", age=" + age + "]";
 }
}

2、创建utils(EntityUtils.java)

package com.jeff.utils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class EntityUtils {
 /**
  * 
  * @description: 实体类转Map
  * @author: Jeff
  * @date: 2019年10月29日
  * @param object
  * @return
  */
 public static Map<String, Object> entityToMap(Object object) {
  Map<String, Object> map = new HashMap<>();
  for (Field field : object.getClass().getDeclaredFields()) {
   try {
    boolean flag = field.isAccessible();
    field.setAccessible(true);
    Object o = field.get(object);
    map.put(field.getName(), o);
    field.setAccessible(flag);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return map;
 }
 /**
  * 
  * @description: Map转实体类
  * @author: Jeff
  * @date: 2019年10月29日
  * @param <T>
  * @param map    需要初始化的数据,key字段必须与实体类的成员名字一样,否则赋值为空
  * @param entity 需要转化成的实体类
  * @return
  */
 public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
  T t = null;
  try {
   t = entity.newInstance();
   for (Field field : entity.getDeclaredFields()) {
    if (map.containsKey(field.getName())) {
     boolean flag = field.isAccessible();
     field.setAccessible(true);
     Object object = map.get(field.getName());
     if (object != null && field.getType().isAssignableFrom(object.getClass())) {
      field.set(t, object);
     }
     field.setAccessible(flag);
    }
   }
   return t;
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  }
  return t;
 }
}

3、创建Map转实体类(TestCopyObj3.java)

package com.jeff;
import java.util.HashMap;
import java.util.Map;
import com.jeff.entity.User;
import com.jeff.utils.EntityUtils;
public class TestCopyObj3 {
 public static void main(String[] args) throws Exception {
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("userName", "Jeff");
  map.put("password", "123456");
  map.put("age", 18);
  System.out.println("Map对象:" + map);
  User user = EntityUtils.mapToEntity(map, User.class);
  System.out.println("User对象:" + user);
 }
}

4、控制台输出结果

Java如何实现实体类转Map、Map转实体类

5、创建实体类转Map(TestCopyObj4.java)

package com.jeff;
import java.util.Map;
import com.jeff.entity.User;
import com.jeff.utils.EntityUtils;
public class TestCopyObj4 {
	public static void main(String[] args) throws Exception {
		User user = new User("Jeff", "123456", 18);
		System.out.println("User对象:" + user);
		Map<String, Object> map = EntityUtils.entityToMap(user);
		System.out.println("Map对象:" + map);
	}
}

6、控制台输出结果

Java如何实现实体类转Map、Map转实体类

Map转实体类或List数组

因为做项目,需要取出复杂的map里的value转为实体类对象和List,在博客里找了很久没有找到合适的方法,于是只能默默探索。。。

map里包含了实体类,list数组,还有普通的key-value,取出我们想要的数据呢?直接取我是取不出来,后来想先转json,在从json里去出对象和list,然后就这么干,废话少说,撸代码!!!

1.先添加maven依赖,这里用alibaba的

<!--alibaba json  -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.46</version>
</dependency>

2.自己写的一个JsonUtil工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
public class JsonUtil<T>{
    
    public static JSONObject mapToJson(Map<String, Object> map) {
        String data = JSON.toJSONString(map);
        return JSON.parseObject(data);
    }
    /**
     * map中取key对应的value
     * @param map
     * @param key
     * @return
     */
    public String mapToString(Map<String, Object> map, String key) {
        JSONObject jsonObject = mapToJson(map);
        return jsonObject.getString(key);
    }
    /**
     * map中取类对象
     * @param map
     * @param clazz
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz, String key) {
        T t = null;
        JSONObject jsonObject = mapToJson(map);
        JSONObject object = jsonObject.getJSONObject(key);
        t = object.toJavaObject(clazz);
        return t;
    }
    /**
     * map中取list
     * @param map
     * @param clazz
     * @param key
     * @return
     */
    public  List<T> mapToList(Map<String, Object> map, Class<T> clazz, String key) {
        List<T> t = null;
        JSONObject jsonObject = mapToJson(map);
        JSONArray array = jsonObject.getJSONArray(key);
        t = array.toJavaList(clazz);
        return t;
    }
}

3.用 postman 发送数据到后台

Java如何实现实体类转Map、Map转实体类

4.后台接收代码

    @RequestMapping(value = "/subjects/subject", method = {RequestMethod.POST})
    public Result addSubject(@RequestBody Map<String, Object> map) {
        //使用json
        JsonUtil jsonUtil = new JsonUtil();
        //获取Subject对象
        Subject subject = jsonUtil.mapToObject(map, Subject.class, "subject");
        //获取List数组
        List<Progress> progressList = jsonUtil.mapToList(map, Progress.class, "progress");
        //获取key对应的值
        String specid = jsonUtil.mapToString(map, "specid");
        //打印输出
        System.out.println(subject);
        for(Progress progress : progressList) {
            System.out.println(progress);
        }
        System.out.println(specid);
        return null;
    }

5.后台输出

到此成功从map里取出对象,list,和key-value

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_45739720/article/details/102807086