【发布时间】:2016-06-16 11:21:00
【问题描述】:
我最近才开始使用 Retrofit + Gson,虽然我四处寻找问题的答案并尝试了几种解决方案,但似乎没有任何效果,而是导致:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期为 BEGIN_OBJECT,但在第 1 行第 2 列路径 $ 处为 BEGIN_ARRAY
首先,返回的 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"
}]
}]
}
}]
这是我的改造客户...
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;
}
}
审查模型...
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...
}
以及我提出请求的片段代码...
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<Reviews>应该是Call<List<Review>>。其余的似乎都很好 -
@Blackbelt 谢谢,实际上我已经尝试过了,但也许我忽略了一些东西。我再试一次。
-
@Blackbelt 谢谢,您的建议和 Blackbelt 的回答同样有效。我以前尝试过这两种方法,但我的错误在于评论课程,你们俩都让我意识到这是错误的一部分。干杯!