我遇到错误:org.json.JSONObject 类型的数据无法转换为 JSONArray
这是我的回复
{
"success": "true",
"data": {
"email": "sample@gmail.com",
"session_code": "samplesession"
}
}
这是我的代码
StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.login, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray details = obj.getJSONArray("data");
if (status_code == 200) {
Log.d("success_to",response);
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
String email = object.getString("email");
Log.d("sample_email", email);
}
finish();
startActivity(new Intent(getApplicationContext(), Profile.class));
}else{
Log.d("error_to","error 404 na");
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我还是 Android 新手,我仍在学习这个过程,有人可以帮助我解决我的问题吗,这确实浪费了我修复这个错误的时间。
最佳答案
您的 json 中没有数组,因此请尝试如下
JSONObject obj = new JSONObject(response);
JSONObject data=obj.optJSONObject("data");
String email = data.getString("email");
从代码中删除以下行
JSONArray details = obj.getJSONArray("data");
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
String email = object.getString("email");
Log.d("sample_email", email);
}
关于java - 我如何循环 JSON 对象的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59950875/