我认为序列名称有问题。我有这个JSON:
{
"current_page": 1,
"data": [
{"Name": "test", "Family": "test"},
{"Name": "test2", "Family": "test2"}
],
"item_page": 2
}
和一个类:
public class UserFetch(){
@SerializedName("current_page")
@Expose
private int currentPage;
@SerializedName("item_page")
@Expose
private int item_page;
@SerializedName("data")
@Expose
private list<User> users = new ArrayList<>();
public UserFetch(){
}
//getter and setter and another constructor not mentioned
}
并且用户类也被序列化:
public class User(){
@SerializedName("Name")
@Expose
private String Name;
@SerializedName("Family")
@Expose
private String Family;
public User(){
}
//getter and setter and another constructor not mentioned
}
当我调用json wia改造并获取数据时(成功满和另一个变量都像current_page
一样工作),但是数组不起作用,当我调用数组项时,将显示IndexOutofBounds。
编辑::这就是我称呼数组对象的方式:
Call<UserFetch> call = userservice.getAllUsers();
call.enqueue(new Callback<UserFetch>() {
@Override
public void onResponse(Call<UserFetch> call, Response<UserFetch> response) {
if(response.isSuccessful()){
Toast.makeText(getActivity(), "SuccessFull!", Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), response.body().getUsers().get(0).getName(), Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "unSuccess", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<StoreFetch> call, Throwable t) {
Toast.makeText(getContext(), "Failure : " + t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:0)
解决方案:
在UserFetch类中编写User类,如下所示:
public class UserFetch() {
@SerializedName("current_page")
@Expose
public int currentPage;
@SerializedName("item_page")
@Expose
public int item_page;
@SerializedName("data")
@Expose
public list<User> users = new ArrayList<>();
public class User(){
@SerializedName("Name")
@Expose
public String Name;
@SerializedName("Family")
@Expose
public String Family;
}
}
代替:
if(response.isSuccessful()){
Toast.makeText(getActivity(), "SuccessFull!", Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), response.body().getUsers().get(0).getName(), Toast.LENGTH_SHORT).show();
}
您的变量必须如图所示是公共的
代替:
if(response.isSuccessful()){
UserFetch userFetch = response.body();
List<UserFetch.User> userList = userFetch.users;
for (UserFetch.User user : userList) {
Toast.makeText(getApplicationContext(), "name : " + user.Name + " family: " + user.Family, Toast.LENGTH_SHORT).show();
}
}
如果需要特定的名称和家庭数据,则可以使用传统的for循环。
希望这会起作用。如有疑问,您可以在下面评论。