如何打印 JSON 对象的字符串
How to print the string of a JSON Object
我正在通过 laravel api 注册用户。响应来自 json 对象。
现在我想在 Toast 中打印这个对象的消息字符串,而不是写 "Acount Successfully created"。我该怎么办
JSON Object
{
"success": true,
"data": {
"token": "//removed",
"name": "Abdullah"
},
"message": "User register successfully."
}
这是 onResponse 方法
OnResponse
@Override
public void onResponse(JSONObject response) {
try {
if ( response.getBoolean("success")) {
Log.i("response", response.toString());
Toast.makeText(RegisterActivity.this, "Account Successfully Created", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Log.e("Response", response.toString());
Toast.makeText(RegisterActivity.this, "" + response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
您可以使用 get(String) 方法访问属性,然后使用 asText();将 属性 的值作为 String:
public void onResponse(JSONObject response) {
try {
if (response.getBoolean("success")) {
Log.i("response", response.toString());
Toast.makeText(RegisterActivity.this, response.get("message").toString(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Log.e("Response", response.toString());
Toast.makeText(RegisterActivity.this, "" + response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我正在通过 laravel api 注册用户。响应来自 json 对象。 现在我想在 Toast 中打印这个对象的消息字符串,而不是写 "Acount Successfully created"。我该怎么办
JSON Object
{ "success": true, "data": { "token": "//removed", "name": "Abdullah" }, "message": "User register successfully." }
这是 onResponse 方法
OnResponse
@Override
public void onResponse(JSONObject response) {
try {
if ( response.getBoolean("success")) {
Log.i("response", response.toString());
Toast.makeText(RegisterActivity.this, "Account Successfully Created", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Log.e("Response", response.toString());
Toast.makeText(RegisterActivity.this, "" + response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
您可以使用 get(String) 方法访问属性,然后使用 asText();将 属性 的值作为 String:
public void onResponse(JSONObject response) {
try {
if (response.getBoolean("success")) {
Log.i("response", response.toString());
Toast.makeText(RegisterActivity.this, response.get("message").toString(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Log.e("Response", response.toString());
Toast.makeText(RegisterActivity.this, "" + response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}