java中Map对象转为有相同属性的类对象(json作为中间转换)
- 准备好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);
}
}
- 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;
}