1

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

enter image description here

Can anyone explain to me the issue and how I can resolve it?

Thanks!

3 Answers 3

3

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();        
Sign up to request clarification or add additional context in comments.

1 Comment

A small note for someone stumbling into this like me. JSONArray extends ArrayList. So if you want you can just do "ArrayList<String> items = obj.getJSONArray("errors"); String[] arr = items.toArray()"
2

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

Comments

1

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
          }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.