Android 如何解析 Json 错误对象
Android how to parser a Json Error Object
我想解析我的 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."]}
这是代码:
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.
In post JSON 字符串 errors
是 JSONArray
而不是 String 所以你应该首先从 JSONObject
得到 errors
然后遍历获取字符串的数组:
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);
}
错误是 JSONArray
:
JSONArray errors = jObject.optJSONArray("errors");
for (int i = 0; i < errors.length(); i++) {
String errorAtIndex = errors.optString(i);
}
来自文档:optString(index)
Returns the value at index if it exists, coercing it if necessary.
我想解析我的 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."]}
这是代码:
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.
In post JSON 字符串 errors
是 JSONArray
而不是 String 所以你应该首先从 JSONObject
得到 errors
然后遍历获取字符串的数组:
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);
}
错误是 JSONArray
:
JSONArray errors = jObject.optJSONArray("errors");
for (int i = 0; i < errors.length(); i++) {
String errorAtIndex = errors.optString(i);
}
来自文档:optString(index)
Returns the value at index if it exists, coercing it if necessary.