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;
}