oshakab
oshakab

Reputation: 349

how do I extract the JSON value?

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();                     
 }

Upvotes: 0

Views: 51

Answers (1)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

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();
}

Upvotes: 1

Related Questions