如何将android JSON数据转换为PHP数组
我有格式的JSON数据
[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"test"}]
现在我想在我的PHP Web系统中获取这些数据。 我将这些数据从android应用程序发送到PHP服务器。我使用下面的代码将它发送到Web服务器。
public JSONObject sendAndGetJSONfromURL(String url,List<NameValuePair> params){ InputStream is = null; String result = ""; JSONObject jArray = null; //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-type", "application/json"); httppost.setHeader("Accept", "application/json"); httppost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); .....
在发送之前,我会打印
jArray.toString()并得到了输出
[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"test"}]
我想知道如何从PHP系统中获取这些值。任何人都可以帮助我吗?
在通过HTTPRequest发送之前,params变量值的输出如下所示
[cartdata=[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"UWUDAMITH"}]]
这可能不是最好的方法,因为我是Java / Android的新手,但它适用于我:)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/save.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
nameValuePairs.add(new BasicNameValuePair("json",jArray.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
这将发送一个帖子到服务器$ _POST ['id'] = 1,然后$ _POST ['json'] =到您的json数据;
这里是save.php。 我实际上保存到MySQL,所以你。
<?php
$server = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id = $_POST["id"];
$json = $_POST["json"];
$sql = "INSERT INTO comments (id, json) ";
$sql .= "VALUES ($id, '$json')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
echo json_decode($json);
?>
使用json_decode()
http://php.net/manual/en/function.json-decode.php
用法: json_decode($json, true)
//将json解码为关联数组
http://php.net/manual/en/function.json-decode.php这应该派上用场。 也请查看http://php.net/manual/en/function.json-encode.php,以获取与该功能完全相反的内容。
链接地址: http://www.djcxy.com/p/21941.html上一篇: How to convert android JSON data into PHP array
下一篇: How do I pass a JSONObject from Android application to a PHP file?