我是android开发的新手,使用volley制作简单的登录应用程序并从服务器获取json响应,如下所示:
json回复: -
{"loginResult":"{\"UserLoginID\":864,\"UserID\":864,\"EmployeeCode\":\"PI4264\",\"Password\":\"XXXX\",\"IsPasswordChanged\":false,\"ModuleName\":\"XXX\",\"ModuleID\":1,\"EmployeeName\":\"XXXX \"}"}
当我尝试解析这个jsonobect时:
19 jsonexception的未终止对象到目前为止,我尝试解析的是
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
int yogs=yog.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
不知道在哪里弄错了任何人都可以教我正确的做法!!!
答案 0 :(得分:1)
您应该将代码更改为:
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
我执行了代码并没有收到错误:
JSONObject yog = new JSONObject("{\"loginResult\":\"{\\\"UserLoginID\\\":864,\\\"UserID\\\":864,\\\"EmployeeCode\\\":\\\"PI4264\\\"," +
"\\\"Password\\\":\\\"XXXX\\\",\\\"IsPasswordChanged\\\":false,\\\"ModuleName\\\":\\\"XXX\\\",\\\"ModuleID\\\":1,\\\"EmployeeName\\\":\\\"XXXX " +
"\\\"}\"}");
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), String.valueOf(yogs), Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
您正在进行不必要的字符串清理。
只需删除replaceAll
命令即可。并使用以下代码:
try {
JSONObject yog = new JSONObject(response);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
System.out.println(yogs);
}
catch (JSONException e) {
e.printStackTrace();
}
此后应该可以正常工作。