通过改造获取对象数组时,错误无法解决方法

时间:2019-04-12 12:48:26

标签: android json list retrofit

我想获取对象数组(JSON),然后获取一些值。

我已尝试完成以下所有操作: How to get array of objects with gson/retrofit?

但是我在Android Studio中遇到提示错误,例如Cannot resolve method 'getId()'

JSON:

[{
    "id": "551454",
    "rights": ["auth", "objects-prepaid-get"],
    "services": [{
        "service_id": "103",
        "options": {
            "sum": 0
        },
        "dismisable": 0
    }],
    "date_activate": "2017-11-11",
    "period": {
        "date_action": "2019-03-29",
        "after": 0
    },
    "ast": {
        "id": "3",
        "services": [{
            "service_id": "4",
            "dismisable": 0
        }, {
            "service_id": "5",
            "dismisable": 0
        }]
    },
    "ast_s": {
        "id": "82",
        "services": [{
            "service_id": "4",
            "dismisable": 0
        }, {
            "service_id": "5",
            "dismisable": 0
        }],
        "date": "2019-03-29",
        "dissmissable": 1
    }
}]

我在活动中正在做什么:

onCreate(){
...
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        SomeAPI userClient2  = retrofit.create(SomeAPI.class);
        getUserInfo();

}

private void getUserInfo() {
        token = AppPreferences.getStringFromSh(getApplicationContext());
        Call<List<User>> call2 = userClient2.getInfoUser("Bearer " + token);

        call2.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.code() == 200){
                        id = response.body().getId(); //id - List<Integer>
                        tvAccount.append(" " + id);

                }
                else {
                    Toast.makeText(UserProfile.this, "Err while loading", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Toast.makeText(UserProfile.this, "error!", Toast.LENGTH_SHORT).show();
            }
        });
    }

在界面中,我有:

@GET("objects")
    Call<List<User>> getInfoUser(@Header("Authorization") String token);

在User.class中,我有:

public class User {
    private List<Integer> id;
 public List<Integer> getId(){
        return id;
    }

    public void setId(List<Integer> id){
        this.id = id;
    }
}

我的代码有什么问题?我在哪里弄错了?

UPD:

尝试过:

            id = response.body().get(0).getId();
            tvAccount.append(" " + id);

获取:

Expected BEGIN_ARRAY but was StRING at line 1 column 9 path $[0].id

2 个答案:

答案 0 :(得分:2)

似乎response.body()返回了List<User>,因此您必须访问列表中的一项。例如:

response.body().get(0).getId();

答案 1 :(得分:0)

您不能直接从列表中获取getId()

List<User> listUser=response.body();

如果您期望有多个用户,则应遍历整个用户列表以获取ID

for (User user : listUser) 
{ 
    List<Integer> listIds=user.getId();
}