如何解码从Android传递的PHP值中的JSON

时间:2014-11-16 17:06:54

标签: php android json

我在做Android应用。在那里我将值传递给PHP文件。在传递给PHP文件之前,我使用log来查看当时我获得所有值的值但是在插入数据时它没有提交。我试了很多,但不知道我哪里出错了。

以下是log cat中的日志:

[{"MNO":"5656565664","Latitude":"17.3731701","Longitude":"78.504573"}]  

以下是doInBackground方法,其中我使用了Log.e

@Override
protected Boolean doInBackground(String... arg0)
{
    Log.e("doInBackground", "doInBackground1");

    Log.e("arg0[0]", arg0[0]);

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();    
    params.add(new BasicNameValuePair("Location", arg0[0]));

    Log.e("doInBackground", "doInBackground2");

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.example.com/insertLocation.php");
    HttpParams httpParameters = new BasicHttpParams();
    httpclient = new DefaultHttpClient(httpParameters);

    Log.e("doInBackground", "doInBackground3");
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response;
        response = httpclient.execute(httppost);        
        StatusLine statusLine = response.getStatusLine();        
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

            Log.e("Google", "Server Responded OK");

        } else {

            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

以下是我尝试插入的insertLocation.php代码:

<?php 

$Location= $_POST['Location'];
$data = json_decode($Location, true);

$mno = $data ->MNO;
$latitude = $data ->Latitude;
$longitude =$data ->Longitude;


//Include db connect class
$hostname_localhost ="localhost";
$database_localhost ="geolocation";
$username_localhost ="abc";
$password_localhost ="abc123";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);    
mysql_select_db($database_localhost, $localhost);

$flag['code']=0;
//Mysql inserting a new 

$result = mysql_query("INSERT INTO location(mno,latitude,longitude) VALUES('$mno','$latitude','$longitude')");  
if($result)
{
    $flag['code']=200;
} 
echo json_encode($flag);
mysql_close($con);
?>

1 个答案:

答案 0 :(得分:1)

$data = json_decode($Location, true);这将返回数组

所以

使用$data[0]['MNO']