5

I'm setting up a RestController using Spring-boot. This project requires me to return a list of object (in this case objects of class Book). How do I do that?

I've tried Arrays.asList() method by passing a object of class Book shown below:

java

@RestController
public class BookController {

    @GetMapping("/books")
    public List<Book> getAllBooks() {

        return Arrays.asList(new Book(1l, "Book name", "Book author"));

    }
}

java

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 + "]";
    }
}

I've got this error "Type mismatch: cannot convert from List<Object> to List<Book>". How can I fix this?

7
  • 4
    why didn't Arrays.asList work? Commented Jun 9, 2019 at 11:16
  • 1
    What problem with your code? did you get any error or any unexpected result? Commented Jun 9, 2019 at 11:18
  • I've got this error "Type mismatch: cannot convert from List<Object> to List<Book>" from the return statement of getAllBooks() method Commented Jun 9, 2019 at 11:21
  • 4
    the code that you share it seems not throwing this error! Commented Jun 9, 2019 at 11:21
  • Adding import java.util.*; and commenting out the jpa annotation makes it compile fine with javac -Xlint:all *.java. (Also, use List.of since Java SE 9.) Commented Jun 9, 2019 at 12:46

1 Answer 1

17

It happened to me several times, and the reason was always that IDE somehow auto imported other Arrays class, from junit package, not the one from java.util. So check your imports part and put import java.util.Arrays; if another Arrays class is imported instead. @Tom Hawtin - tackline suggested similar, but nothing else is needed except correct import.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.