我有一个类,我在其中尝试将类 Bookstore 的对象和书籍列表添加到对象列表中。但是,我在添加书籍列表时遇到了类型转换错误。
这是我的 REST 客户端:
public class Test {
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
ResponseList responseList = service.path("rest").path("BookMain/get").accept(MediaType.APPLICATION_XML).get(ResponseList.class);
BookStore bs = (BookStore) responseList.getList().get(0);
ArrayList<Book> lb = (ArrayList<Book>) responseList.getList().get(1);
}
这是我的课程,它正在添加 Bookstore 对象和书籍列表:
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_XML)
public ResponseList addObjects() {
BookStore bookstore = new BookStore();
bookstore.setName("Prateek Bookstore");
bookstore.setLocation("Vasanth Nagar");
Book book1 = new Book();
book1.setName("Book2");
book1.setAuthor("Author2");
Book book2 = new Book();
book2.setName("Book3");
book2.setAuthor("Author3");
ArrayList<Book> Blist = new ArrayList<Book>();
Blist.add(book1);
Blist.add(book2);
ArrayList<Object> list = new ArrayList<Object>();
list.add(bookstore);
list.addAll(Blist);
ResponseList books = new ResponseList();
books.setList(list);
return books;
}
这是错误:
Exception in thread "main" java.lang.ClassCastException:Book cannot be cast to java.util.ArrayList
这是我的响应列表:
@XmlRootElement
@XmlSeeAlso({BookStore.class,Book.class,Hello.class})
public class ResponseList {
private List<Object> list;
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
}
这是书店类:
@XmlRootElement
@XmlType(propOrder = {"name", "location"})
public class BookStore {
private String name;
private String location;
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public void setName(String name) {
this.name = name;
}
public void setLocation(String location) {
this.location = location;
}
}
这是书类:
@XmlRootElement
public class Book {
private String name;
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
云谁告诉我我做错了什么?