Reputation: 12431
Hi I am trying to display the error messages stored in the following JSONObject obj
{"errors":["nickname is already taken,","email is already taken"]}
This is my implementation:
TextView errorMsg;
errorMsg = (TextView)findViewById(R.id.register_error);
String[] errorArray = (String[])obj.get("errors");
errorMsg.setText(errorArray[0]);
Toast.makeText(getApplicationContext(), errorArray[0], Toast.LENGTH_LONG).show();
However when trying to run the code, I get a ClassCastException
Can anyone explain to me the issue and how I can resolve it?
Thanks!
Upvotes: 1
Views: 12670
Reputation: 425
Here it's an JsonArray
and not an String array
so use library like simple-json from google and parse using below code:
JSONArray erroeArray= (JSONArray) jsonObject.get("errors");
Iterator<String> iterator = erroeArray.iterator();
while (iterator.hasNext()) {
//yourcode here
}
Upvotes: 1
Reputation: 11953
The 'erros' array is not String
array. So get value in JSONArray
do this.
JSONArray errorArray = obj.getJSONArray("errors");
you can convert it.
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Upvotes: 2
Reputation: 332
The "errors" array in your example isn't a String array (String[]), it's a JSONArray.
Instead, do
JSONArray errorArray = obj.getJSONArray("errors");
then,
errorMsg.setText(errorArray.getString(0));
Toast.makeText(getApplicationContext(), errorArray.getString(0), Toast.LENGTH_LONG).show();
Upvotes: 3