我一直在关注tutorial (老实说,我是复制粘贴,因此我不知道为什么它不起作用,因为我没有改变任何东西)并且我有这个字符串响应,我需要将其转换为 Json 对象。
响应=
Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}
在 JSONObject jObj = new JSONObject(response);
的 try
之后,我的程序跳转到异常并显示一条消息:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONObject.toString()
是response
的结构还是什么?
这是我使用它的地方:
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String surname = user.getString("surname");
String address = user.getString("address");
String email = user.getString("email");
// Inserting row in users table
db.addUser(name, surname, address, email);
// Launch main activity
Intent intent = new Intent(LoginScreen.this,
MainMenu.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
最佳答案
在将响应转换为 JSON 对象之前,从响应中删除 Config.php\r\n
前缀。
关于java - 尝试创建 JSONObject 以无法评估 org.json.JSONObject.toString() 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160525/