-3

I have a server response from server like this -

[
    {
        "status": "ok"
    }
]

In my app I am using volley to load data:

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest({api_url}, script
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    // Retrieve "status" = "ok"
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            });

I want to get "ok" as string so i can compare with something. How can i get that ?

SamyB
  • 235
  • 1
  • 9
mukeshsoni
  • 483
  • 8
  • 29

2 Answers2

1

You receive a JSONArray at the begining, not a JSONObject. You should replace it

    JsonArrayRequest jsonObjectRequest = new JsonArrayRequest({api_url},
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray jsonArray) {
                    JSONObject statusJson = jsonArray.optJSONObject(0);
                    String status = statusJson.optString("status");
                    Log.d("Status", "Status value == [ " + status + " ]");
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            });
SamyB
  • 235
  • 1
  • 9
0

There is a much simpler solution:

JSON.parse(response[0]).status

JSON.parse is a Javascript function that parse a string object to a valid JSON like object :)

Morgan Le Floc'h
  • 314
  • 2
  • 4
  • 12