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

标签 android json string toast

我正在通过 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/

相关文章:

android - android模拟器中的互联网问题

android - onStop() 没有被调用?

android - Google Maps Android API v2 仅适用于一部手机

c# - jquery如何在c#中编写正确的json对象

javascript - 我如何在 Zapier 触发器中对数组进行 JSON.parse?

c - C 中字符串数组的成员之间交换

c++ - 为什么 boost::locale::to_title 没有返回预期的输出?

java - 在运行时编译 renderscript 代码

javascript - 将 JSON 保存到 SQL

c - 尝试输出此函数时我什么也没得到\空白