繁体   English   中英

如何循环我的 JSON 对象的响应?

[英]How can i loop the response of my JSON Object?

我有一个data of type org.json.JSONObject cannot be converted to JSONArraydata of type org.json.JSONObject cannot be converted to JSONArray错误data of type org.json.JSONObject cannot be converted to 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);
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM