预期发送到服务器的JSON
{"syncsts":
[
{"status":"1","Id":"9"},
{"status":"1","Id":"8"}
]
}
期望在服务器上检索JSON Object的方式
$arr = $_POST['syncsts']
(I think)
$ arr应该[{"地位":"1","Id":"9"},{"地位":"1","Id":"8"}]
JsonObjectRequest函数和JSON样式参数
public void updateMySQLSyncSts(final ArrayList<HashMap<String, String>> lt){
JSONArray arr = new JSONArray(lt);
JSONObject js = new JSONObject();
try {
js.put("syncsts",arr);
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("MainActivity",js.toString());
String url = "http://10.0.3.2/insight/mysqlsqlitesync/updatesyncsts.php";
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("MainActivity",error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(req);
}
PHP脚本/**
* Updates Sync status of Users
*/
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["syncsts"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->updateSyncSts($data[$i]->Id,$data[$i]->status);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->Id;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->Id;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
我使用上面的函数发送JSON格式的参数随着我的post请求。当$_POST["syncsts"]行在PHP脚本中执行时,会抛出以下错误:
JSONObject toString()和logcat
中显示的Error10-04 21:59:23.523 2062-2062/? I/MainActivity: {"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}
10-04 21:59:23.767 2062-2062/? I/MainActivity: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
显示服务器接收到的内容的PHP脚本(调试)
file_put_contents('test.txt', file_get_contents('php://input'));
$arr = $_POST['syncsts'];
echo $arr;
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo json_encode($age);
用法
{"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}
请告诉我什么是错误的JSON格式,我试图发送到我们的服务器是在Java中生成的。
看起来错误是在服务器的响应。onResponse(JSONObject response)
期望结果是正确的jsonobject。检查在回显结果之后是否显示任何其他元素(例如错误消息)。你可以检查它从浏览器使用一个chrome扩展称为邮差使用,你可以尝试发送POST和GET请求手动到服务器