java.lang.IllegalStateException:预期BEGIN_ARRAY但是BEGIN_OBJECT(Retrofit 2)

时间:2016-11-08 09:07:45

标签: java android retrofit rx-java

从服务器接收数据时出现错误: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接口:

@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);
}

班组:

public class Group {

    private String name;
    private String description;

    public Group(String name, String description) {
        this.name = name;
        this.description = description;
    }

}

1 个答案:

答案 0 :(得分:2)

我添加了班级组:

library(ggplot2)
df <- group_by(mpg, manufacturer) %>%
  summarise(cty = mean(cty), hwy = mean(hwy)) %>%
  ungroup()

df <- melt(df, id.vars = "manufacturer")

ggplot() +
  geom_bar(data =df, aes(x = variable, y = value), stat = "identity") +
  facet_grid(manufacturer ~ ., switch = "y")+
 theme(strip.text.y = element_text(angle = 180))

并将API接口中的代码更改为:

public class Groups {

    @SerializedName("group")
    List<Group> group;
}

此应用程序开始工作后没有错误。