我试图发送这个json数据形式android到php服务器



我试图将这个json数据从android发送到php服务器。
我的json数据{email:"user111@gmail.com",密码:"00000"},有谁能告诉我如何解码PHP服务器中的json数据吗

这是我的php服务器代码

<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`
 if(!isset($_POST['params'])){
 $decoded=json_decode($_POST['params'],true)
  $email=json_decode['email'];
 $pass=json_decode['password'];
 // connecting to db
 $db = new DB_CONNECT();`

$result = mysql_query("SELECT *FROM user WHERE email = $email");
 if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {`
        $result = mysql_fetch_array($result);
        $this->mylog("email".$email.",password".$pass);
        if($pass==$result[password]){
        echo " password is correct";
        $response["code"]=0;
        $response["message"]="sucess";
        $response["user_id"]=$result["userid"];
        $response["firstname"]=$result["fname"];
        $response["lastname"]=$result["lname"];
        echo json_encode($response);
        }else{
        $response["code"]=3;
        $response["message"]="invalid password and email";
        echo json_encode($response);
        }
    }else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";
// echoing JSON response
echo json_encode($response);
}
}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response  
echo json_encode($response); }?>

**this my android code json praser **

     public JSONObject loginUser(String email, String password) {
    Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
    loginURL2.appendPath("ws_login.php");
    JSONObject loginJSON = new JSONObject();
    try {
        loginJSON.put("email", email);
        loginJSON.put("password", password);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
            loginJSON);
    return json;
}

this my android json data send function

     public JSONObject getJSONFromUrl(String url, JSONObject params) {
    // Making HTTP request
    try {
        // defaultHttpClient
        // boolean status=isNetworkAvailable();
        HttpParams param = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(param, 10000);
        HttpConnectionParams.setSoTimeout(param, 10000);
        DefaultHttpClient httpClient = new DefaultHttpClient(param);
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(params.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                CONTENT_TYPE_JSON));
        httpPost.setEntity(se);
        Log.d("URL Request: ", url.toString());
        Log.d("JSON Params: ", params.toString());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int code = httpResponse.getStatusLine().getStatusCode();
        if (code != 200) {
            Log.d("HTTP response code is:", Integer.toString(code));
            return null;
        } else {
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    } catch (ConnectTimeoutException e) {
        // TODO: handle exception
        Log.e("Timeout Exception", e.toString());
        return null;
    } catch (SocketTimeoutException e) {
        // TODO: handle exception
        Log.e("Socket Time out", e.toString());
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        jsonResp = sb.toString();
        Log.d("Content: ", sb.toString());
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting Response " + e.toString());
        return null;
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(jsonResp);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON Object
    return jObj;
}
public boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

如果$_POST['params']是一个JSON编码的字符串,您只需要调用json_decode一次,而不是您所显示的多次。

$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];

应该注意的是,你的问题中的字符串不是有效的JSON,因为电子邮件和密码也需要引号。

你可以在这里做json_decode函数的实时测试:http://php.fnlist.com/php/json_decode

你可以在这里验证你的JSON:http://jsonlint.com

最新更新