如何从Volley响应中获取JSON值?

时间:2018-08-20 23:46:04

标签: android json android-volley response

响应格式为{"status":"201","message":"OTP is created and sent."},我需要获取状态和消息值,但是String name = response.getString("name");显示红线错误。

这是我的代码:

public void sendData() {
    final JSONObject json = new JSONObject();
    final TextView serverResp = findViewById(R.id.connectionStatus);
    try {
        json.put("mobile", "12312312");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String url = getResources().getString(R.string.url_login);

    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(REQ_TAG, response.toString());
                    String name = response.getString("name");
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            serverResp.setText("Error getting response\n" + error.toString());
            Log.d(REQ_TAG, "Error: " + error.toString()
                    + "\nStatus Code " + error.networkResponse.statusCode
                    + "\nResponse Data " + error.networkResponse.data
                    + "\nCause " + error.getCause()
                    + "\nmessage" + error.getMessage());
        }
    });

    jsonObjectRequest.setTag(REQ_TAG);
    requestQueue.add(jsonObjectRequest);
    // do i need the following line?
    //RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}

1 个答案:

答案 0 :(得分:0)

因为JSON响应中没有密钥name

尝试

 String status= response.getString("status");
 String message= response.getString("message");