0

I am getting and error response from server in android studio. how do I extract the values.

Json:

{
  "error": {
    "phone": [
      "The phone field is required."
    ]
  }
}

Code:

 try {
     JSONArray arr = new JSONArray(response);
     for (int i = 0; i < arr.length(); i++) {
        JSONObject mJsonObject = arr.getJSONObject(i);
        Log.d("OutPut", mJsonObject.getString("phone"));
     }
 } catch (JSONException e) {
     e.printStackTrace();                     
 }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
oshakab
  • 299
  • 1
  • 3
  • 11

1 Answers1

1

Actually your response is an object not an array. Try below:

String response = "{\"error\":{\"phone\":[\"The phone field is required.\"]}}";

try {
    JSONObject jsonObject = new JSONObject(response);
    JSONObject errorObject = jsonObject.optJSONObject("error");
    JSONArray phoneArray = errorObject.getJSONArray("phone");

    for (int i = 0; i < phoneArray.length(); i++) {
        String  errorString = phoneArray.optString(i);
        Log.d("OutPut", errorString);
    }
} catch (JSONException e) {
    e.printStackTrace();
}
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46