Retrofit2:ClassCastException:无法将java.util.ArrayList强制转换为retrofit2.Call
作者:互联网
请帮助Retrofit2.我在翻新中非常新.
我创建简单的服务器应用程序.
应用程序管理日记列表:在内存列表中添加日记,然后按ID返回日记.
有一个Journal.java:
public class Journal {
private AtomicInteger getNewId = new AtomicInteger(0);
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
public Journal(String name) {
this.id = getNewId.incrementAndGet();
this.name = name;}
public Integer getId() {return id;}
public String getName() {return name;}
}
有一个控制器接口:
public interface JournalController {
@GET("journal")
Call<List<Journal>> getJournalList();
@GET("journal/{id}")
Call<Journal> getJournal(@Path("id") Integer id);
@POST("journal")
Call<Journal> addJournal(@Body Journal journal);
}
这是接口实现:
@Controller
public class JournalControllerImpl implements JournalController {
// An in-memory list that the controller uses to store the Journals
private List<Journal> journals = new ArrayList<>();
@RequestMapping(value= "journal", method=RequestMethod.GET)
public @ResponseBody Call<List<Journal>> getJournalList() {
return (Call<List<Journal>>) journals;}
@RequestMapping(value= "journal/{id}", method= RequestMethod.GET)
public @ResponseBody Call<Journal> getJournal(@Path("id") Integer id) {
Journal journal = journals.get(id);
return (Call<Journal>) journal;}
@RequestMapping(value= "journal", method= RequestMethod.POST)
public @ResponseBody Call<Journal> addJournal(@Body Journal journal) {
journals.add(journal);
return (Call<Journal> ) journal; }
}
该应用程序成功启动.应用程序启动期间的控制台输出:
Mapped “{[/journal],methods=[GET]}” onto public retrofit2.Call> main.JournalControllerImpl.getJournalList()
Mapped “{[/journal],methods=[POST]}” onto public retrofit2.Call main.JournalControllerImpl.addJournal(main.Journal)
Mapped “{[/journal{/id}],methods=[GET]}” onto public retrofit2.Call main.JournalControllerImpl.getJournal(java.lang.Integer)
比我尝试在浏览器上运行URL http://localhost:8080/journal(或GET HttpRequest http://localhost:8080/journal).
应用程序输出中存在错误:
“ … java.lang.ClassCastException:无法将java.util.ArrayList强制转换为retrofit2.Call …”
你能猜出是什么问题吗?
将java.util.ArrayList转换为Call真的有问题吗? (我尝试了CopyOnWriteArrayList,但这无济于事.
先感谢您.
解决方法:
呼叫< T>是Retrofit类,只需要存在于客户端,它是对潜在调用外部API的抽象.
我不确定服务器使用的是哪种类型的库,但是无法转换完全不相关的类. (例如ArrayList< T>呼叫< List< T>))
通常,该库将为您处理序列化,因此在服务器端,您只需直接返回要发送的对象即可:
@RequestMapping(value= "journal", method=RequestMethod.GET)
public @ResponseBody List<Journal> getJournalList() {
return journals;}
标签:classcastexception,retrofit2,call,server-side,java 来源: https://codeday.me/bug/20191118/2027063.html