我正在尝试将我的数据从localhost读取到Android Studio。我用排球来做到这一点。我有问题从我的json获取值。这是我的json。
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
这是Android中的代码。
JsonObjectRequest jsonObjReq = new JsonObjectRequest(urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String username = response.getString("username");
String section = response.getString("section");
String year = response.getString("year");
jsonResponse = "";
jsonResponse += "Username: " + username + "\n\n";
jsonResponse += "Section: " + section + "\n\n";
jsonResponse += "Year: " + year + "\n\n\n";
txtView.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
感谢您的帮助。
答案 0 :(得分:1)
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject.getJSONArray("studentList");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String username = jsonObject1.getString("username");
String section = jsonObject1.getString("section");
String year = jsonObject1.getString("year");
Toast.makeText(MainActivity.this, username + " " + section + " " + year, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
希望这有帮助
答案 1 :(得分:0)
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
JSON响应的结构是一个包含列表的Object,其中包含student类型的对象
其中包含用户名和&amp;密码,您直接尝试从外部对象获取用户名。
String username = response.getString("username");
首先,您需要从列表中提取对象,然后访问用户名。
JsonArray jsonArr = response.getJSONArray("studentList");
JsonObject studentObj = jsonArr.get(0);
答案 2 :(得分:0)
JSONArray parentArray = response.getJSONArray("studentList");
if (parentArray.length() == 0) {
//no students
} else {
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String username = finalObject.getString("username");
String password = finalObject.getString("password");
String section = finalObject.getString("section");
String year = finalObject.getString("year");
}
}
这将循环遍历&#34; studentList&#34;
中的每个学生确保导入JSONArray import org.json.JSONArray;