我正在使用 Spring-boot 设置一个 RestController。这个项目要求我返回一个对象列表(在这种情况下是类 Book 的对象)。我怎么做?
我已经通过传递类 Book 的对象来尝试 Arrays.asList() 方法,如下所示:
爪哇
@RestController
public class BookController {
@GetMapping("/books")
public List<Book> getAllBooks() {
return Arrays.asList(new Book(1l, "Book name", "Book author"));
}
}
Run Code Online (Sandbox Code Playgroud)
爪哇
public class Book {
Long id;
String name;
String author;
public Book(Long id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
我有这个错误"Type mismatch: cannot convert from List<Object> to List<Book>"。我怎样才能解决这个问题?
它发生在我身上好几次,原因总是 IDE 以某种方式自动导入了其他 Arrays 类,来自 junit 包,而不是来自 java.util 的那个。因此,请检查您的导入部分,并import java.util.Arrays;输入是否导入了另一个 Arrays 类。@Tom Hawtin-tackline 建议类似,但除了正确导入之外不需要其他任何东西。
| 归档时间: |
|
| 查看次数: |
1495 次 |
| 最近记录: |