android - 获取 JSONArray 时 Retrofit2 + Gson IllegalStateException

标签 android gson retrofit2

我最近才开始使用 Retrofit + Gson,虽然我四处寻找问题的答案并尝试了几种解决方案,但似乎没有任何效果,而是导致:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

首先,返回的 JSONArray 看起来像这样:

[{
    "id": 23545,
    "title": "some title",
    "description": "some description",
    "questions": {
        "text": [{
            "question": "Some question"
        }, {
            "question": "Some other question"
        }],
        "checkbox": [{
            "question": "Some question",
            "options": [{
                "value": "3",
                "correct": "1"
            }, {
                "value": "2",
                "correct": "0"
            }, {
                "value": "1",
                "correct": "0"
            }]
        }]
     }
}]

这是我的 Retrofit 客户端...

public class ApiClient {

    public static final String BASE_URL = "http://somewhere.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        }
        return retrofit;
    }

    public static ApiInterface getApiInterface() {
        return getClient().create(ApiInterface.class);
    }

}

这是界面...

public interface ApiInterface {

    @Headers("Content-Type: application/x-www-form-urlencoded")
    @GET("rest/reviews.json")
    Call<Reviews> getReviews(@Header("Cookie") String cookie);

}

这是评论模型:

public class Reviews {

    private ArrayList<Review> reviews = new ArrayList<>();

    public ArrayList<Review> getReviews() {
        return reviews;
    }

    public void setReviews(ArrayList<Review> reviews) {
       this.reviews = reviews;
    }

}

和 Review 模型......

public class Review {

    @SerializedName("id") private Integer id;
    @SerializedName("title") private String title;
    @SerializedName("description") private String description;
    @SerializedName("questions") private Questions questions;

    public String getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    etc...
}

以及我发出请求的 fragment 代码......

ArrayList<Review> reviews = new ArrayList<>();

ApiInterface apiInterface = ApiClient.getApiInterface();

Call<Reviews> call = apiInterface.getReviews(cbi.onGetCookie());

call.enqueue(new Callback<Reviews>() {
    @Override
    public void onResponse(Call<Reviews> call, Response<Reviews> response) {
        if(response.isSuccessful()) {
            reviews = response.body().getReviews();
            // pass on to RecyclerView adapter
        } else {
            // handle fail
        }
    }
    @Override
    public void onFailure(Call<Reviews> call, Throwable t) {
        Log.e(TAG, t.toString());
    }
});

Gradle 依赖项以防有人感兴趣...

compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

我理解错误消息,我只是想弄清楚如何让 Gson 期待 JSONArray。我确定我的错误很明显,但我没有看到或理解它。在此先感谢您的帮助!

最佳答案

如下更改代码,它应该可以工作:

Call<Review []> call = apiInterface.getAppraisals(cbi.onGetCookie());

call.enqueue(new Callback<Review []>() {
    @Override
    public void onResponse(Call<Review []> call, Response<Review[]> response) {
        if(response.isSuccessful()) {
            reviews = response.body();
            // pass on to RecyclerView adapter
        } else {
            // handle fail
        }
    }
    @Override
    public void onFailure(Call<Review[]> call, Throwable t) {
        Log.e(TAG, t.toString());
    }
});

I have changes Reviews to Review[] because in your response there is no key "reviews" which contains array of Review.

关于android - 获取 JSONArray 时 Retrofit2 + Gson IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857683/

相关文章:

android - 用于 Eclipse 和 Android 开发的 Mercurial 忽略文件

java - Gson.toJson Stackoverflow错误

android - 应用程序崩溃 : Fatal Exception: io. reactivex.exceptions.CompositeException

android - 改造 2 第 1 行第 1 列路径的输入结束 $

android - 创建完整的移动应用程序与创建进入处理移动设备的服务器的应用程序

android - 撤销权限 android.permission.CALL_PHONE

android - 使用 gson 制作 Jsonobject

android - 配置 gson 为 wcf web 服务序列化日历类型

Android Retrofit 2 文件上传不起作用

android - 约束布局指南