所以我正在使用 AsyncHttpClient 库解析Github用户数组。这个解析的结果是带有Json响应的String对象(它仍然是草稿):
private String getResponse()
{
AsyncHttpClient client=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("since","0");
client.get("https://api.github.com/users", params,
new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
try {
String content = new String(arg2, "UTF-8");
//content is json response that can be parsed.
response = content;
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
});
if (response.isEmpty())
return "Users not found";
else
return response;
}
问题是如何从这个回复中解析?我的意思是,当你不知道Github用户api的结构时,你怎么做? 我试图像这样解决这个问题:
private ArrayList<String> parseResponse (String response)
{
try {
JSONObject reader = new JSONObject(response);
JSONObject nameObject = reader.getJSONObject("????"); //I don't know
//how that object is called since no idea about structure!
name = nameObject.getString("name");
userList.add(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return userList;
}
如何正确地迭代这个以获得每个用户?
提前致谢。
答案 0 :(得分:3)
只需在浏览器中导航至https://api.github.com/users
即可查看。
示例:强>
[
{
"login": "",
"id": 0,
"avatar_url": "",
"gravatar_id": "",
"url": "",
"html_url": "",
"followers_url": "",
"following_url": "",
"gists_url": "",
"starred_url": "",
"subscriptions_url": "",
"organizations_url": "",
"repos_url": "",
"events_url": "",
"received_events_url": "",
"type": "User",
"site_admin": false
},
{...}
]
您可以从[]
看到顶级元素是JSONArray。因此,您需要获取此数组,然后在每个索引处访问JSONObject。
JSONArray users = new JSONArray(response);
for(int i=0; i<users.length(); i++){
JSONObject user = users.getJSONObject(i);
String login = user.getString("login");
}
答案 1 :(得分:1)
要解析响应中每个用户的登录,您必须迭代JSONArray,如下所示:
try {
JSONArray readerArray = new JSONArray(result);
for(int i=0;i<readerArray.length();i++){
JSONObject userObject = (JSONObject) readerArray.get(i);
String login = userObject.getString("login");
//add login to your ArrayList here
}
} catch (JSONException e) {
e.printStackTrace();
}
其中result
是带有Json
响应的字符串。