当从服务器接收数据时,我收到这样的错误:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
。什么会导致这样的错误?以及如何修复它?
我从服务器收到的 JSON:
{
"group": [
{
"name": "Group1",
"description": "Test Group 1"
},
{
"name": "Group2",
"description": "Group Name Updated"
}
]
}
API接口(interface)如下:
@GET("groups")
Observable <List<Group>> getAllGroups(@Header("Authorization") String auth,
@Header("Content-type") String contentType,
@Header("Accept") String accept
);
我接收数据的方法:
private void getAllGroups() {
String credentials = "admin" + ":" + "admin";
final String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
String contentType = "application/json";
String accept = "application/json";
Subscription subscription = App.service.getAllGroups(basic, contentType, accept)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(groups -> {
groupList.addAll(groups);
}, throwable -> {
Log.e("All group error", String.valueOf(throwable));
});
addSubscription(subscription);
}
类(class)组:
public class Group {
private String name;
private String description;
public Group(String name, String description) {
this.name = name;
this.description = description;
}
}
最佳答案
我添加了类(class)组:
public class Groups {
@SerializedName("group")
List<Group> group;
}
并将API接口(interface)中的代码更改为:
@GET("groups")
Observable <Groups> getAllGroups(@Header("Authorization") String auth,
@Header("Content-type") String contentType,
@Header("Accept") String accept
);
应用程序开始正常工作后,不会出现错误。
关于java.lang.IllegalStateException : Expected BEGIN_ARRAY but was BEGIN_OBJECT (Retrofit 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40482858/