您好我开始学习为Android构建应用程序。我正在使用Retrofit来获得json响应。这是结构:
{"Results": [
{
"Id": 1,
"Feed": 1,
"Title": "title",
"Summary": "Text",
"PublishDate": "2015-09-12T21:45:16",
"Image": "imageurl",
"Url": "websiteurl",
"Related": [
"relatedurl",
"relatedurl"
],
"Categories": [
{
"Id": 61,
"Name": "Sport"
},{
"Id": 63,
"Name": "Voetbal"
}
],
"IsLiked": false
}
],
"NextId": 4285 }
这些是我的模特:
public class Result {
private String NextId;
private Results[] Results;
}
public class Results {
private String Url;
private String Feed;
private String Image;
private String Id;
private List<String> Related;
private List<Categories> Categories;
private String PublishDate;
private String Title;
private String IsLiked;
private String Summary;
}
public class Categories {
private String Name;
private String Id;
}
我的界面如下:
public interface WebService {
@GET("articles")
Call<List<Result>> Articles();
}
我在运行时遇到致命错误:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
谁能告诉我我做错了什么?
答案 0 :(得分:3)
java.lang.IllegalStateException:预期BEGIN_ARRAY但是 BEGIN_OBJECT在第1行第2列路径$
端点返回JSONObject
,但您要告知返回JSONArray
的改造。
更改
Call<List<Result>> Articles();
与
Call<Result> Articles();
您发布的NextId
中的Id
和JSON
也不是String
答案 1 :(得分:1)
在Android工作室中添加DTO插件。 数据传输对象(DTO)生成器,它根据给定的源生成Java类。
这是您正确的模型类
{
public static class Results {
@SerializedName("Id")
public int id;
@SerializedName("Feed")
public int feed;
@SerializedName("Title")
public String title;
@SerializedName("Summary")
public String summary;
@SerializedName("PublishDate")
public String publishdate;
@SerializedName("Image")
public String image;
@SerializedName("Url")
public String url;
@SerializedName("Related")
public List<Related> related;
@SerializedName("Categories")
public List<Categories> categories;
@SerializedName("IsLiked")
public boolean isliked;
}
public static class Categories {
@SerializedName("Id")
public int id;
@SerializedName("Name")
public String name;
}
}
答案 2 :(得分:0)
id,feed和NextId不是字符串,您使用错误的结构获取数据。尝试
Call<Result> Articles()
答案 3 :(得分:0)
进行以下更改
您的界面应更改为
public interface WebService {
@GET("articles")
Call<Result> Articles();
}
在您的模型类中
public class Result {
private String NextId;
private List<Results> Results;
}