Reputation: 201
So I'm parsing Github user array using AsyncHttpClient library. And the result of this parsing is String object with Json response (its still a draft):
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;
}
The question is how do I parse from this response? I mean, how do you do this when you don't know the structure of Github user api? I'm trying to solve this smth like this:
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;
}
And how to iterate this properly to get every user?
Thanks in advance.
Upvotes: 0
Views: 635
Reputation: 6892
To parse the login from every user on the response, you have to iterate over the JSONArray, like this:
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();
}
Where result
is a String with your Json
response.
Upvotes: 1
Reputation: 8695
Just navigate to https://api.github.com/users
in your browser and take a look.
Example:
[
{
"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
},
{...}
]
You can see from the []
that the top-level element is a JSONArray. So you need to get this array, and then access the JSONObject at each index.
JSONArray users = new JSONArray(response);
for(int i=0; i<users.length(); i++){
JSONObject user = users.getJSONObject(i);
String login = user.getString("login");
}
Upvotes: 3