【发布时间】:2015-09-26 14:18:37
【问题描述】:
我是第一次使用 Retrofit,放弃了带有 AsyncTask 的传统 httpclient。而且我在理解 Retrofit 的真正工作原理时遇到了问题。
我收到此错误:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
完整的网址是:https://api.github.com/users/basil2style
Json 返回
{
"login": "basil2style",
"id": 1285344,
"avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/basil2style",
"html_url": "https://github.com/basil2style",
"followers_url": "https://api.github.com/users/basil2style/followers",
"following_url": "https://api.github.com/users/basil2style/following{/other_user}",
"gists_url": "https://api.github.com/users/basil2style/gists{/gist_id}",
"starred_url": "https://api.github.com/users/basil2style/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/basil2style/subscriptions",
"organizations_url": "https://api.github.com/users/basil2style/orgs",
"repos_url": "https://api.github.com/users/basil2style/repos",
"events_url": "https://api.github.com/users/basil2style/events{/privacy}",
"received_events_url": "https://api.github.com/users/basil2style/received_events",
"type": "User",
"site_admin": false,
"name": "Basil",
"company": "MakeInfo",
"blog": "http://www.themakeinfo.com",
"location": "India",
"email": "basiltalias92@gmail.com",
"hireable": true,
"bio": null,
"public_repos": 39,
"public_gists": 3,
"followers": 28,
"following": 129,
"created_at": "2011-12-26T00:17:22Z",
"updated_at": "2015-09-23T18:36:51Z"
}
下面是我的代码。
MainActivity
public class MainActivity extends ActionBarActivity {
List<GitHub> examplelist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestAdapter restAdapter = new RestAdapter.Builder().
setEndpoint("https://api.github.com").build();
GitHubAPI gitapi = restAdapter.create(GitHubAPI.class);
gitapi.getFeed(new Callback<List<GitHub>>() {
@Override
public void success(List<GitHub> github, Response response) {
examplelist = github;
Log.d("Size: ", Integer.toString(examplelist.size()));
}
@Override
public void failure(RetrofitError error) {
Log.d("Error: ", error.getLocalizedMessage());
}
});
}
}
型号
我只对从 Github api 获取登录、id、avatar_url 和 gravater_id 数据感兴趣
public class GitHub {
String login;
String id;
String avatar_url;
String gravatar_id;
public String getLogin() {
return login;
}
public String getId() {
return id;
}
public String getAvatar_url() {
return avatar_url;
}
public String getGravatar_id() {
return gravatar_id;
}
}
界面
public interface GitHubAPI {
@GET("/users/basil2style")
public void getFeed( Callback<List<GitHub>> response);
}
请我真的需要完成这项工作,我很沮丧。
【问题讨论】:
-
您要求取回
List。没有List。如果您查看您的 JSON,它不是 JSON 数组。它是一个 JSON 对象。要么你有错误的 URL,要么你需要调整你的代码以期望只有一个GitHub实例,而不是 N。 -
返回的数据是地图/字典,而不是列表。
-
@KentHawkings,我不知道。 :(,我想我需要了解更多。无论如何,谢谢。
-
为什么人们不赞成这个问题?人们确实来这里寻求答案,你知道,并期待正确的答案。有礼貌..