首页 > 解决方案 > Retrofit2 的问题 - Android

问题描述

当 json 数据如下所示时,我无法检索数据:

{
"": "",
"": ""
}

但一切都是这样工作的:

[
{
"": "",
"": ""
}
]

我的问题是我真的需要像第一个选项一样检索我的数据。

public interface API {
    String BASE_URL = "https://cloud-functions-d378b.firebaseapp.com/";

    @GET("PLAYER_API.json")
    Call<List<Players>> getPlayer();
}


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_info);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();


        API api = retrofit.create(API.class);

        Call<List<Players>> call = api.getPlayer();

        onResponse will be executed

        call.enqueue(new Callback<List<Players>>() {
            @Override
            public void onResponse(Call<List<Players>> call, Response<List<Players>> response) {


                List<Players> playersList = response.body();


                String[] players = new String[playersList.size()];


                for (int i = 0; i < playersList.size(); i++) {
}

我希望能够以这种格式检索我的数据:

{
"": "",
"": ""
}

标签: androidretrofit2

解决方案


只需更改 api 调用的声明:

Call<Players> getPlayer();

推荐阅读