我正在尝试发送帖子数据但是收到错误,无法创建json对象。 请帮忙。
我从java发送这个:我收到错误我需要请告诉我他们是否有任何更正的PHP。我不知道php
JSON:
{
"tagtrack_scans": {
"product_id": "1",
"scanned_as": "12334556",
"email": "aabce@gmail.com"
}
}
PHP代码:
<?php
$json_data=$_POST['tagtrack_scans'];
$data=json_decode($json_data, true);
echo $data['email'];
echo $data['scanned_as'];
echo $data['product_id'];
$dbhost = 'localhost:2082';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'tagtrack_scans' );
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected to tagtrack_scans';
$sql="INSERT INTO tagtrack_scans (email, scanned_as, product_id)
VALUES ($email, $canned_As, $product_id)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysql_close($conn);
?>
用于将JSON发送到PHP的Java代码:
JSONObject jsonObjSend = new JSONObject();
JSONObject jsonObj = new JSONObject();
try {
// Add key/value pairs
jsonObjSend.put("email", "ane@gmail.com");
jsonObjSend.put("canned_As", "12334556");
jsonObjSend.put("product_id", "1");
jsonObj.put("tagtrack_scans", jsonObjSend);
// Add a nested JSONObject (e.g. for header information)
// JSONObject header = new JSONObject();
// header.put("deviceType","Android"); // Device type
// header.put("deviceVersion","2.0"); // Device OS version
// header.put("language", "es-es"); // Language of the Android client
// jsonObjSend.put("header", "");
// Output the JSON object we're sending to Logcat:
Log.i("MainActivity", jsonObj.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObjRecv = HttpClient.SendHttpPost("http://abc.php", jsonObj);
答案 0 :(得分:0)
根据this answer,您没有以正确的方式获取JSON数据。
请改为尝试:
<?php
$json_data=file_get_contents("php://input");
$data=json_decode($json_data, true);
if(isset($data['tagtrack_scans'])){
$data = $data['tagtrack_scans'];
}
else{
die('Unexpected JSON received');
}
echo $data['email'];
echo $data['scanned_as'];
echo $data['product_id'];
$dbhost = 'localhost:2082';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'tagtrack_scans' );
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected to tagtrack_scans';
$sql="INSERT INTO tagtrack_scans (email, scanned_as, product_id)
VALUES ($email, $canned_As, $product_id)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysql_close($conn);
?>
请注意,这很快且很脏并且未经测试。在生产中使用之前,您应该对其进行改进。