Android如何解析Json错误对象

时间:2022-10-29 16:58:34

I want to parse my json Errors Object

我想解析我的json错误对象

this is the json :

这是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."]}

here is the code :

这是代码:

JSONObject jObject = new JSONObject(result);

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

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

The Problem is that this is how the string is displaying :

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

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

I want to remove the [] and the "". Can someone advice pls. thanks

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

to be like:

像是:

-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 个解决方案

#1


2  

In post JSON string errors is JSONArray instead of String so you should first get errors from JSONObject then iterate over Array to get Strings:

在帖子中,JSON字符串错误是JSONArray而不是String,因此您应首先从JSONObject获取错误,然后迭代Array以获取字符串:

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

#2


2  

errors is a JSONArray:

错误是JSONArray:

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

From the documentation: optString(index)

来自文档:optString(index)

Returns the value at index if it exists, coercing it if necessary.

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

#1


2  

In post JSON string errors is JSONArray instead of String so you should first get errors from JSONObject then iterate over Array to get Strings:

在帖子中,JSON字符串错误是JSONArray而不是String,因此您应首先从JSONObject获取错误,然后迭代Array以获取字符串:

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

#2


2  

errors is a JSONArray:

错误是JSONArray:

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

From the documentation: optString(index)

来自文档:optString(index)

Returns the value at index if it exists, coercing it if necessary.

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