简体   繁体   中英

How to read response from a POST volley?

I'm really new on android and I'm wokring on a login system, I'm using volley to post the data....the problem thatm I'm having is when i try to read the response.... the response looks like this:

{"st":"no","Message":"Error"}

I'm trying to access only st or message is there a way to do that ? I tried doing:

response[i] ----Array type expexted found ' org.json.JSONObject'

 JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) { 
                    Log.e(TAG, "Response: " + response.length());
                    for (int i = 0; i < response.length(); i++) {
                        Log.e(TAG, "Values: " + response);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace(); 
                }
            });

            Volley.newRequestQueue(this).add(jsonRequest);

You could use

response.getString("Message")

to get a message from given JSON

 @Override
 public void onResponse(String response) {
    try {
           JSONObject api_response = new JSONObject(response);
           String message = api_response.getString("Message")
       } catch (JSONException e) {
            e.printStackTrace();           
       }

Its important to catch the json exception just in case the response string cannot be converted to json object. Then use the getString() to get the message from the created json object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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