将java中Map对象转为有相同属性的类对象(json作为中间转换)

时间:2021-03-13 02:59:48

java中Map对象转为有相同属性的类对象(json作为中间转换)

  1. 准备好json转换工具类
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper(); public static String objectToString(Object object) throws JsonProcessingException {
String s;
if (object instanceof String) {
s = String.valueOf(object);
} else {
s = objectMapper.writeValueAsString(object);
}
return s;
} public static <T> T stringToObject(String json,Class<T> object) throws IOException {
return objectMapper.readValue(json,object);
}
}
  1. map转为User对象简单示例
public class test {
public static void main(String[] args) throws IOException { Map map=new HashMap();
map.put("userId",111);
map.put("userName","张三");
User user = JsonUtil.stringToObject(JsonUtil.objectToString(map), User.class);
System.out.println(user);
}
} @Data
class User{
private int userId;
private String userName;
}