当 Json root 不是数组而是对象时,如何根据不同的 url 解析 JSON 数据,反之亦然?
How to parse JSON data when Json root is not an array but an object and vice-versa, based on different urls?
我正在尝试构建一个使用 github api 的 android 应用程序。
我遇到 JSON 解析问题。
我有一个查找 JSON 数组并生成相应的 JSON 数据以在 UI 中显示它们的函数,但问题是该函数仅在 JSON 根目录下有效是一个数组。
对于前
当 url 为“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”时,JSON 根成为一个对象。我现在如何解析它以显示 UI 中的数据?
我必须为 JSON 对象编写单独的函数吗??
** java 函数是 **
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");
}
}
答案是肯定的。在这里,您尝试在单个函数中解析不同类型的对象(用户列表和特定用户信息)。这违反了单一职责原则。
您可以将此功能一分为二(解析用户列表和用户数据),但最好为此使用 Retrofit 2。
我正在尝试构建一个使用 github api 的 android 应用程序。 我遇到 JSON 解析问题。 我有一个查找 JSON 数组并生成相应的 JSON 数据以在 UI 中显示它们的函数,但问题是该函数仅在 JSON 根目录下有效是一个数组。 对于前 当 url 为“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”时,JSON 根成为一个对象。我现在如何解析它以显示 UI 中的数据? 我必须为 JSON 对象编写单独的函数吗??
** java 函数是 **
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");
}
}
答案是肯定的。在这里,您尝试在单个函数中解析不同类型的对象(用户列表和特定用户信息)。这违反了单一职责原则。 您可以将此功能一分为二(解析用户列表和用户数据),但最好为此使用 Retrofit 2。