【问题标题】:PHP json_encoded message match with java json objectPHP json_encode 消息与 java json 对象匹配
【发布时间】:2016-10-08 10:33:16
【问题描述】:

我正在尝试为我的 Android 应用创建响应侦听器。

我正在尝试从我的 php 代码中获得响应,如下所示:

Response.Listener<String> responseListener = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {
            Log.i("tagconvertstr", "["+response+"]");
            JSONObject jsonResponse = new JSONObject(response);
            JSONArray success = jsonResponse.getJSONArray("success");
            JSONArray success2 = jsonResponse.getJSONArray("no");
            if (success.toString() == "{"success"}") {
                Intent intent = new Intent(EnglishRegisterSite.this, UK.class);
                EnglishRegisterSite.this.startActivity(intent);
            } else if (success2.toString() == "{"no"}") {
                AlertDialog.Builder builder = new AlertDialog.Builder(EnglishRegisterSite.this);
                builder.setMessage("You are not 18 years old! kid!")
                       .setNegativeButton("Retry", null)
                       .create()
                       .show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }   
};

PHP 响应如下所示:

$response = array();
$response["no"];  
echo json_encode($response);

如果我将 php 数组更改为 $response["no"] = true; 并创建一个布尔值,那么我可以让它像这样工作:

 boolean success2 = jsonResponse.getboolean("no");

但这不行,因为那样我只能有两种情况。要么失败,要么成功。但是我想要实现的是创建更多的场景来说明它是否失败然后指定它失败的原因。就像在这个例子中一样。如果用户正在尝试注册并且尚未满 18 岁,则会弹出一条消息,说明这是问题所在。

因此,我需要从 PHP 向 Java 发送某种 JSON 编码的消息,我可以在 Java 中检查这些消息。

有谁知道我如何做到这一点?

【问题讨论】:

    标签: java php android json response


    【解决方案1】:

    试试这样的json响应内容:

    {
        success: true,
        msg: "Here can be anything you want to display."
    }
    

    如果成功则注册,否则显示msg内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2013-02-23
      • 2018-12-09
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多