Issue
I am trying to build an android app that uses the github api. I am facing an issue with JSON parsing. I have a function that looks for JSONArray and produces the corresponding JSON data to show them in the UI, but the problem is the function works only when the JSON root is an array. For ex- when the url is "https://api.github.com/users", it works perfect, since the root is an array but now when I go to url such as "https://api.github.com/users/mojombo", the JSON root becomes an object. How do I parse it now in order to show the data in the UI ?? Do I have to write separate function for JSONObjects??
**The java function is **
private void makeJSON(String res) throws JSONException {
JSONArray root = new JSONArray(res);
for (int i =0; i<root.length();i++){
JSONObject jsonObject= root.getJSONObject(i);
String name = jsonObject.getString("login");
int id = jsonObject.getInt("id");
}
}
Solution
The answer is yes. Here you try to parse different types of objects (users list and particular user info) in single function. This is violation of single responsibility principle. You can divide this function in 2 (to parse users list and user data) but better is to use Retrofit 2 for this.
Answered By - Peter Staranchuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.