如何使用Json解析来自服务器的数据?

时间:2017-10-09 10:15:20

标签: php android json

这是我的php文件。我想在android中解析数据作为JSON对象。我能做到这一点。

<?php
include("../include/connection.php");
    $old_pass="1234";
    $new_pass="123";
    $re_pass="123";
    $contact_no="8285663445";
     $chg_pwd="select * from users where contact_no='$contact_no'";
    $data=mysqli_query($conn,$chg_pwd) or die(mysqli_error($conn));
    $chg_pwd1=mysqli_fetch_array($data);
     $data_pwd=$chg_pwd1['password'];
    if($data_pwd==$old_pass){
    if($new_pass==$re_pass){
        $update_pwd="update users set password='$new_pass' where contact_no='$contact_no'";
        $updata=mysqli_query($conn,$update_pwd) or die(mysqli_error($conn));
        $json = array("status" => 1, "msg" => "password reset successfully");
    }
    else{

        $json = array("status" => 0, "msg" => "Your new and Retype Password is not match!");
    }
    }
    else
    {
    $json = array("status" => 0, "msg" => "Request method not accepted");
    }
header('Content-type: application/json');
echo json_encode($json);
?>

这是我的android功能,我试图从服务器获得响应。

private void signupTrace(String response ) throws JSONException {
    JSONObject jsonObject= new JSONObject(response);
    if(jsonObject.getString("status").equals("1")){
        Log.e("log", "" + response);
        String mesg= jsonObject.getString("msg");
        Log.e("msg",""+mesg);
        Toast.makeText(Change_Password.this,mesg, Toast.LENGTH_SHORT).show();
        finish();
    }
    else if (jsonObject.getString("status").equals("0")){
        String mesg= jsonObject.getString("msg");
        Toast.makeText(Change_Password.this,mesg, Toast.LENGTH_SHORT).show();
    }
    else {
        Snackbar.make(findViewById(android.R.id.content), " Server failed", Snackbar.LENGTH_LONG)
                .setAction("Undo", null)
                .setActionTextColor(Color.RED)
                .show();
    }
}

这就是我在logcat中获得的内容。

  

0-09 15:33:23.578 23721-25138 / com.pickpamphlet.easydeals E / mapvalue {old_pass = 12345,contact_no = 8947897487,re_pass = zxcvbnm,new_pass = zxcvbnm}
  10-09 15:33:24.813 23721-23721 / com.pickpamphlet.easydeals E / log:{&#34; status&#34;:0,&#34; msg&#34;:&#34;请求方法不被接受& #34;}&#39;

1 个答案:

答案 0 :(得分:0)

Android代码中的JSON解析正确完成。

1234不是数据库中的密码。请检查您的情况是否正确。

if($data_pwd==$old_pass){

}
else
{
    $json = array("status" => 0, "msg" => "Request method not accepted");
}

正确检查你的php条件并确保你传递的是正确的值。