要在Android中使用Retrofit解析对象为列表,你需要进行以下步骤:
implementation 'com.squareup.retrofit2:retrofit:2.x.x'
implementation 'com.squareup.retrofit2:converter-gson:2.x.x'
public interface ApiService {
@GET("api/endpoint")
Call> getItems();
}
public class Item {
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
// getters and setters
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call> call = apiService.getItems();
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
if (response.isSuccessful()) {
List- items = response.body();
// 处理解析后的对象列表
} else {
// 处理请求失败情况
}
}
@Override
public void onFailure(Call
> call, Throwable t) {
// 处理网络请求失败情况
}
});
以上就是使用Retrofit解析对象为列表的基本步骤和代码示例。你可以根据自己的需求进行相应的修改和扩展。