我正在尝试使用Retrofit 2进行JSON解析。我必须为我的项目打电话。这是我的代码:
retrofit2.Call<Map<String, Channel>> call =restInterface.getChannels();
call.enqueue(new Callback<Map<String, Channel>>() {
@Override
public void onResponse(Response<Map<String, Channel>> response) {
Map<String, Channel> body = response.body();
for (Channel channel : body.values()) {
System.out.println(channel.getSong());
}
}
@Override
public void onFailure(Throwable t) {
// TODO
}
});
我收到不兼容的类型错误,Android Studio建议转到此处:
retrofit2.Call<Map<String, Channel>> call =restInterface.getChannels();
对此:
retrofit2.Call<List<Channel>> call =restInterface.getChannels();
我知道这是因为Retrofit的原始类型,但是对于我的项目,我必须执行此调用。在这里,您可以看到我的JSON在API中的样子:
{
"channel0":{
"song":"Cry Cry",
"artist":"Oceana",
"duration":"180",
"playedat":"1545158211",
"image_extralarge":"https:\/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/550513f3aaa5b80648972e715af345e5.png"
},
"channel1":{
"song":"Phantom Of The Opera",
"artist":"Iron Maiden",
"duration":"420",
"playedat":"1545158002",
"image_extralarge":"https:\/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/b2cf018fb80147428b698452b2512996.png"
},
"channel2":{
"song":"Carmen Cubana",
"artist":"Klazz Brothers",
"duration":"180",
"playedat":"1545158161",
"image_extralarge":"https:\/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/d518730378364a72ab98460bd0fe3d1a.png"
},
"channel3":{
"song":"Shut Up And Let Me Go",
"artist":"The Ting Tings",
"duration":"120",
"playedat":"1545158234",
"image_extralarge":"https:\/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/c5805b786a3e4f19b747c7a3dbb41d15.png"
},
"channel4":{
"song":"The Racing Rats",
"artist":"Editors",
"duration":"240",
"playedat":"1545158095",
"image_extralarge":"https:\/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/62544562d1904884b6e47804cf1ede1d.png"
}
}
那么,我该怎么办呢?我对该主题了解不多,因此我完全愿意就问题提出建议或示例。感谢您的帮助。
答案 0 :(得分:1)
这是您如何定义翻新服务界面的问题。在某个地方,您应该有一个interface
如下所示:
public interface MyRetrofitService {
@GET("/some/url")
Call<List<Channel>> getChannels();
}
您将不得不更改它以返回Map<String, Channel>
而不是列表:
public interface MyRetrofitService {
@GET("/some/url")
Call<Map<String, Channel>> getChannels();
}