无法从响应发布方法凌空android

时间:2018-08-14 16:19:19

标签: android json android-volley

我已经成功登录,现在作为响应,我想从响应中获取值,但不要获取值,请检查我哪里出错了

 StringRequest strReq = new StringRequest(Request.Method.POST,
            URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();
                Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
                JSONObject jObj = new JSONObject(response.toString());
                semester = jObj.getJSONObject("data").optString("semester");
                regno = jObj.getJSONObject("data").optString("registration_number");
                name = jObj.getJSONObject("data").optString("name");
                mobile = jObj.getJSONObject("data").optString("mobile");

json响应:{“ status”:true,“ data”:{“ id”:“ 1”,“ registration_number”:“ 10000”,“ name”:“ imran”,“ mobile”:“ 000423001178”, “学期”:“ 3”}}

2 个答案:

答案 0 :(得分:1)

您可以尝试使用getString()方法而不是optString。如果没有需要名称的字段,它将给您例外。另外,您只能获得“数据”对象一次,然后使用它:

            JSONObject jObj = new JSONObject(response.toString());
            JSONObject dataJson = jObj.getJSONObject("data");
            semester = dataJson.getString("semester");
            regno = dataJson.getString("registration_number");
            name = dataJson.getString("name");
            mobile = dataJson.getString("mobile");

希望它会对您有所帮助。

答案 1 :(得分:0)

尝试:  JSONObject jObj =新的JSONObject(response);

获取响应的第一行