0

How can I parse the following JSON using Android Volley?

[ { "msg": "success", "id": "1542", "firstname": "Sam", "lastname": "Benegal", "email": "bs@gmail.com", "mobile": "8169830000", "appapikey ": "f82e4deb50fa3e828eea9f96df3bb531" } ]

  • 3
    Possible duplicate of [How to parse JSON with Volley?](https://stackoverflow.com/questions/42601036/how-to-parse-json-with-volley) – Natig Babayev Jan 13 '19 at 16:34

2 Answers2

0

That looks like pretty standard JSON, so Volley's JsonObjectRequest and JsonArrayRequest request types should parse it for you. For example:

JsonArrayRequest request = new JsonArrayRequest(
        Request.Method.GET,
        "https://yoururl",
        null,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONArray response) {
                JSONObject msg1 = response.getJSONObject(0);
                String firstName = msg.getString("firstname") // Sam
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO
            }
        }
);

Code example adapted from the documentation, here: https://developer.android.com/training/volley/request#request-json.

Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
0

try this

StringRequest stringRequest = new StringRequest(URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONArray jsonArray1 = new JSONArray(response);
                            for (int i = 0; i < jsonArray1.length(); i++) {

                                JSONObject object = jsonArray1.getJSONObject(i);

                                {
                                    Toast.makeText(this, ""+object.getString("msg")+"\n"+object.getString("id"), Toast.LENGTH_SHORT).show();

                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
Community
  • 1
  • 1
Rajasimman R
  • 496
  • 4
  • 14
  • if you have more then one JSONObject you need for loop else you directly get. JSONObject object = jsonArray1.getJSONObject(0); – Rajasimman R Jan 13 '19 at 22:24