[英]ClassCastException: JSONArray cannot be cast to java.lang.String[]
Hi I am trying to display the error messages stored in the following JSONObject obj 嗨,我正在尝试显示存储在以下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 但是,当尝试运行代码时,我得到了ClassCastException
Can anyone explain to me the issue and how I can resolve it? 谁能向我解释这个问题以及如何解决?
Thanks! 谢谢!
The 'erros' array is not String
array. “错误”数组不是String
数组。 So get value in JSONArray
do this. 因此,在JSONArray
获取价值即可。
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"));
}
The "errors" array in your example isn't a String array (String[]), it's a JSONArray. 您的示例中的“错误”数组不是String数组(String []),而是JSONArray。
Instead, do 相反,做
JSONArray errorArray = obj.getJSONArray("errors");
then, 然后,
errorMsg.setText(errorArray.getString(0));
Toast.makeText(getApplicationContext(), errorArray.getString(0), Toast.LENGTH_LONG).show();
Here it's an JsonArray
and not an String array
so use library like simple-json from google and parse using below code: 这是一个JsonArray
而不是String array
因此请使用类似Google的 simple-json之类的库,并使用以下代码进行解析:
JSONArray erroeArray= (JSONArray) jsonObject.get("errors");
Iterator<String> iterator = erroeArray.iterator();
while (iterator.hasNext()) {
//yourcode here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.