-1
我的應用程序嘗試使用Retrofit
和Gson
使用API。預計BEGIN_ARRAY,但是BEGIN_OBJECT與Gson和翻新
我的要求是https://nahuatiliztli.herokuapp.com/laws.json
,它返回:
[{"id":1,"title":"Constitución Política de los Estados Unidos Mexicanos","url":"http://www.diputados.gob.mx/LeyesBiblio/pdf/1_29ene16.pdf","created_at":"2016-07-10T02:36:00.641Z","updated_at":"2016-07-10T02:36:00.641Z"}]
我的代碼的結構如下...
我的模型是Law
類:
public class Law {
@SerializedName("id")
private Integer mId;
@SerializedName("title")
private String mTitle;
@SerializedName("url")
private String mUrl;
public Law(Integer id, String title, String url) {
mId = id;
mTitle = title;
mUrl = url;
}
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String url) {
mUrl = url;
}
}
我的回答抽象是LawsResponse
等級:
public class LawsResponse {
private List<Law> mLaws;
public List<Law> getLaws() {
return mLaws;
}
public void setLaws(List<Law> laws) {
mLaws = laws;
}
}
我對Law
模型服務接口:
public interface LawsService {
@GET("https://nahuatiliztli.herokuapp.com/laws.json")
Call<LawsResponse> listLaws();
}
我的適配器是LawsApiAdapter
:
public class LawsApiAdapter {
private static LawsService API_SERVICE;
public static LawsService getInstance() {
if (API_SERVICE==null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(buildLawsApiGsonConverter()))
.build();
API_SERVICE = retrofit.create(LawsService.class);
}
return API_SERVICE;
}
private static Gson buildLawsApiGsonConverter() {
return new GsonBuilder()
.registerTypeAdapter(
LawsApiAdapter.class,
new LawsDeserializer())
.create();
}
}
我已經嘗試了許多建議,張貼在該網站,但它仍然拋出這個錯誤:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
我通過閱讀許多文章瞭解到它期望Json對象,它正在接收一個Json數組,但的確如此,但我不知道如何使其工作。