gpt4 book ai didi

android - 如何打印 JSON 对象的字符串

转载 作者:行者123 更新时间:2023-11-29 23:11:02 26 4
gpt4 key购买 nike

我正在通过 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();以字符串形式获取属性值:

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();
}
}

关于android - 如何打印 JSON 对象的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com