我正在尝试通过改造获取一些数据,并且我遇到了此错误。我了解错误是什么,但我不知道如何解决:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
我试图在这里的其他问题中找到答案,但是我找不到类似我的问题的东西...
我的接口代码:
public interface ApiInterface {
@GET("api/category")
Call<Category> getBusinessCategory();
}
我要调用改造的班级代码:
private Call<Category> mCall;
mCall = apiService.getBusinessCategory();
mCall.enqueue(new Callback<Category>() {
@Override
public void onResponse(Call<Category> call, Response<Category> response) {
if (response.isSuccess()) {
Log.e(TAG, response.toString());
} else {
Toast.makeText(getApplication(), "No conexion", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Category> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
这是JSON:
[
{
"id": 1,
"name": "FOOD",
"imageRef": "v1475594353/categories/a",
"translate": null
},
{
"id": 2,
"name": "CAR",
"imageRef": "v1475594195/categories/b",
"translate": null
}
]
类别类别:
public class Category implements Serializable {
@SerializedName("category")
@Expose
private final static String TAG = "Category";
private String imageRef = "";
private Long id;
private String name;
private String translate;
private transient Bitmap image;
... Getters and setters
apiclient类
public class ApiClient {
public static final String BASE_URL = "http://xxxxx/";
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 interface ApiInterface {
@GET("api/category")
Call<List<Category>> getBusinessCategory(); }
和可变MCALL:
private Call<List<Category>> mCall;
在这里我编辑了您的代码:
public interface ApiInterface {
@GET("api/category")
Call<List<Category>> getBusinessCategory();
}
您的API返回数组,但您正在尝试将其施加到一个对象。
编辑:
private Call<List<Category>> mCall;
mCall = apiService.getBusinessCategory();
mCall.enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
if (response.isSuccess()) {
Log.e(TAG, response.toString());
} else {
Toast.makeText(getApplication(), "No conexion", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Log.e(TAG, t.toString());
}
});