实体类对象转Map对象

使用Fastjson

public <T> Map<String, Object> toMapByJson(T obj) {
    // 默认序列化为数字类型的时间戳
    // String jsonStr = JSON.toJSONString(obj);

    // Fastjson内置了一个默认的日期格式yyyy-MM-dd HH:mm:ss,
    // 可以通过在调用JSON.toJSONString时传入SerializerFeature.WriteDateUseDateFormat来启用。
    // 通过修改默认的时间格式,结合启用默认日期格式,也可以达到按指定日期格式序列化的目的
    // JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    String jsonStr = JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
    Map<String, Object> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {
    });
    return map;
}

使用反射

public <T> Map<String, Object> toMapByReflect(T obj) {
      Field[] fields = obj.getClass().getDeclaredFields();
      Map<String, Object> map = new HashMap<>();

      try {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          for (Field f : fields) {
              f.setAccessible(true);
              Object val = f.get(obj);
              if (f.getType() == Date.class) {
                  map.put(f.getName(), sdf.format(val));
              } else {
                  map.put(f.getName(), val);
              }
          }
      } catch (IllegalArgumentException | IllegalAccessException e) {
          e.printStackTrace();
      }

      return map;
  }

Map对象转实体类对象

使用Fastjson

public <T> T toObjByJson(Map<String, Object> map, Class<T> type) {
    // 日期格式参照上文
    T t = JSON.parseObject(JSON.toJSONString(map), type);
    return t;
}

使用反射

public <T> T toObjByReflect(Map<String, Object> map, Class<T> type) {
    T obj = null;
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        obj = type.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field f : fields) {
            int mod = f.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            f.setAccessible(true);
            if (map.containsKey(f.getName())) {
                if (f.getType() == Date.class) {
                    f.set(obj, sdf.parse((String) map.get(f.getName())));
                } else {
                    f.set(obj, map.get(f.getName()));
                }
            }
        }

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | ParseException e) {
        e.printStackTrace();
    }

    return obj;
}

测试

新建实体类

public class Person {
    private Integer id;
    private String name;
    private Date birthDay;

    public Person() {

    }

    public Person(Integer id, String name, Date birthDay) {
        this.id = id;
        this.name = name;
        this.birthDay = birthDay;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", birthDay=" + birthDay + "]";
    }
}

测试用例

Person p = new Person(1, "Jack", new Date());
TestCopy obj = new TestCopy();
Map<String, Object> map = obj.toMapByJson(p);
System.out.println(map);

Map<String, Object> map2 = obj.toMapByReflect(p);
System.out.println(map2);

Person p1 = obj.toObjByReflect(map, Person.class);
System.out.println(p1);

Person p2 = obj.toObjByReflect(map2, Person.class);
System.out.println(p2);


输出结果
版权声明:本文为有点盐原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/saltish/p/16694397.html