Spring Rest接口返回ArrayList报错:No converter异常
问题解决:No converter for [class java.util.ArrayList] with preset Content-Type 'null'
1. 修正代码中的大小写语法错误
你的代码存在几处Java语法错误,会导致Bean初始化或对象实例化失败,这是引发问题的潜在原因:
PostmanProductDao类的构造方法名必须与类名完全一致:
// 错误写法 public postmanProductDao(){...} // 正确写法 public PostmanProductDao(){ list = new ArrayList<>(); list.add(new PostmanProduct(100,"Ipod","Apple")); list.add(new PostmanProduct(102,"Samsung Buds","Samsung")); }
- 实例化
PostmanProduct时类名需首字母大写:
// 错误写法 new postmanProduct(...) // 正确写法 new PostmanProduct(...)
2. 确保JSON序列化依赖存在
Spring需要JSON转换器来将ArrayList序列化为JSON格式,需根据项目类型确认依赖:
- Spring Boot项目:确保
pom.xml(Maven)或build.gradle(Gradle)包含spring-boot-starter-web依赖,它自带Jackson转换器:
Maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Gradle:
implementation 'org.springframework.boot:spring-boot-starter-web'
- 普通Spring项目:手动添加Jackson依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- 使用最新稳定版 --> </dependency>
3. 优化控制器注解(规范简化)
@RestController注解已包含@ResponseBody,可移除方法上的重复注解:
@RestController @RequestMapping("/postman") public class PostManController { @Autowired private PostmanProductDao postmanProductDao; @GetMapping(value = "/hi") public String showPostman(){ return "Hey, I am the postman. the new Buddy."; } @GetMapping(value = "/Products", produces = MediaType.APPLICATION_JSON_VALUE) public List<PostmanProduct> getProducts(){ return this.postmanProductDao.getProducts(); } }
4. 保证PostmanProduct类符合序列化要求
Jackson序列化需要实体类满足以下条件:
- 拥有公共无参构造方法
- 字段具备getter方法(或用Lombok简化)
示例PostmanProduct类:
public class PostmanProduct { private int id; private String name; private String brand; // 无参构造方法 public PostmanProduct() {} // 带参构造方法 public PostmanProduct(int id, String name, String brand) { this.id = id; this.name = name; this.brand = brand; } // getter和setter方法 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } }
若使用Lombok,可直接添加注解自动生成所需方法:
@Data @AllArgsConstructor @NoArgsConstructor public class PostmanProduct { private int id; private String name; private String brand; }
完成以上操作后重启项目,用Postman发送GET请求即可正常返回JSON格式的数组列表。
内容的提问来源于stack exchange,提问作者Jahedul Islam
相关产品推荐
相关产品推荐

