springboot怎么将List集合数据转成JSON数组
Spring Boot 默认使用Jackson框架将Java对象转换成JSON格式。要转换List集合数据为JSON数组,可以采用以下两种方法:
1.使用@ResponseBody注解
在Spring Boot中,可以使用@ResponseBody注解标注要返回的List集合数据,让Spring自动将其转换成JSON数组。例如:
@GetMapping("/list")
@ResponseBody
public List<User> getUserList() {
List<User> userList = userService.getUserList();
return userList;
}
2.使用ObjectMapper转换
除了使用@ResponseBody注解外,还可以使用ObjectMapper将List集合数据转换成JSON数组。例如:
@GetMapping("/list")
public String getUserList() throws Exception {
List<User> userList = userService.getUserList();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(userList);
return json;
}
需要注意的是,在使用ObjectMapper转换时,需要处理异常。同时,ObjectMapper默认使用ISO-8601日期格式化器,如果需要使用其他日期格式,需要自定义日期格式化器。
浙公网安备 33010602011771号