Spring WebMVC无额外依赖时如何自动转换Java对象与ArrayList为JSON?
未引入GSON等第三方库时,Spring WebMvc 5.3.22如何自动将Java对象/ArrayList转为JSON?
我在项目里只引入了spring-webmvc 5.3.22依赖,没有添加GSON这类第三方JSON处理库,但下面的控制器代码能正常返回JSON数组,想搞清楚Spring是怎么完成自动转换的。
控制器代码
package com.damian.springwebmvc.controllers; import com.damian.springwebmvc.dto.Customer_DTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/json") public class JSONHandler { public JSONHandler() { System.out.println("JSONHandler instantiated via constructor!"); } @GetMapping public List<Customer_DTO> getJSON() { ArrayList<Customer_DTO> customer_dtos = new ArrayList<>(); customer_dtos.add(new Customer_DTO("THIS IS A RESPONSE", "THIS IS A RESPONSE.", "THIS IS A RESPONSE.", 0.0)); customer_dtos.add(new Customer_DTO("THIS IS A RESPONSE", "THIS IS A RESPONSE.", "THIS IS A RESPONSE.", 0.0)); customer_dtos.add(new Customer_DTO("THIS IS A RESPONSE", "THIS IS A RESPONSE.", "THIS IS A RESPONSE.", 0.0)); customer_dtos.add(new Customer_DTO("THIS IS A RESPONSE", "THIS IS A RESPONSE.", "THIS IS A RESPONSE.", 0.0)); return customer_dtos; } }
项目依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.22</version> </dependency>
核心原理说明
- 默认集成Jackson:Spring WebMvc 5.3.22会通过依赖传递自动引入Jackson相关组件(主要是
jackson-databind),不需要手动添加Jackson依赖。Jackson是Spring官方默认的JSON处理库,替代了早期的其他方案。 - @RestController触发消息转换:
@RestController注解包含了@ResponseBody,它会告诉Spring:控制器方法的返回值要直接作为HTTP响应体输出,而不是跳转视图。 - HttpMessageConverter完成序列化:当方法返回
List<Customer_DTO>时,Spring会根据请求的Accept头(默认匹配application/json)选择对应的HttpMessageConverter。默认情况下,MappingJackson2HttpMessageConverter会被选中,它基于Jackson实现Java对象到JSON的序列化:- 对于
ArrayList这类集合,Jackson会自动将其序列化为JSON数组格式; - 对于
Customer_DTO这类自定义对象,Jackson会通过类中的getter方法读取属性值,将其序列化为JSON对象。
- 对于
- 自动配置支持:Spring WebMvc的自动配置机制会自动注册
MappingJackson2HttpMessageConverter到容器中,无需手动配置,只要依赖存在就会生效。
内容的提问来源于stack exchange,提问作者Damian Peiris.
相关产品推荐
相关产品推荐

