我需要显示在会员注册响应,下面是我的JSON响应。我应该显示密码太短(最小为5个字符)到一个字符串
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
同时,我需要解析从以下JSON数据的响应,签名已被占用
{错误:{签名:“已经采取”]}}
请告诉我如何解析来自JSON数据的特定数据。提前致谢!!!!
您可以使用以下方法来解析您的数据。
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
您可以替换像下面的代码不需要符号:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
您可以使用谷歌的GSON库,使用以下步骤做:
build.gradle(Module:app)
文件相关。
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
对于GSON库,click here的最新版本Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
如果你需要将对象转换为JSON字符串,可以使用下面的代码:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
请确保你设计你的对象适用于JSON字符串匹配的数据类型。如果你不知道的JSON数据类型,你可以使用this site或任何解析,并查看网站进行查看。
希望能帮助到你!
刚刚尝试这一点,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}