Android如何解析Json错误对象

时间:2015-01-07 09:42:05

标签: java android json parsing

我想解析我的json Errors Object

这是json:

{"errors":["The name must be at least 4 characters.","The username must be at least 3 characters.","The password must be at least 6 characters."]}

这是代码:

JSONObject jObject = new JSONObject(result);

if (jObject.has("errors")){
// PARSE RESULT 
String errors = jObject.getString("errors");

Utils.makeAlertDialog(getActivity(), "Ops!", errors, false);

问题是这是字符串的显示方式:

["The name must be at least 4 characters.","The username must be at least 3 characters.","The password must be at least 6 characters."]

我想删除[]和“”。有人可以建议。谢谢

就像:

-The name must be at least 4 characters.
-The username must be at least 3 characters. 
-The password must be at least 6 characters.

2 个答案:

答案 0 :(得分:2)

在帖子中,JSON字符串errorsJSONArray而不是字符串,因此您应首先从errors获取JSONObject,然后迭代数组以获取字符串:

JSONArray arrArrors = jObject.getJSONArray("errors");
//iterate to arrArrors get all values
for(int i=0;i<arrArrors.length;i++) {
  String error = arrArrors.optString(i);
  Log.i("JSONDATA","error :: "+error);
}

答案 1 :(得分:2)

错误是JSONArray

JSONArray errors = jObject.optJSONArray("errors");
for (int i = 0; i < errors.length(); i++) {
    String errorAtIndex = errors.optString(i);
}

来自文档:optString(index)

  

返回索引处的值(如果存在),必要时强制转换它。