[英]Volley's JsonObjectRequest gives "org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject" exception
{"syncsts":
[
{"status":"1","Id":"9"},
{"status":"1","Id":"8"}
]
}
$arr = $_POST['syncsts']
(I think ) (我认为 )
$arr should have [{"status":"1","Id":"9"},{"status":"1","Id":"8"}] $arr 应该有 [{"status":"1","Id":"9"},{"status":"1","Id":"8"}]
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);
}
/**
* 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);
I am using the above function to send JSON formatted parameter along with my post request.我正在使用上述函数将 JSON 格式的参数与我的帖子请求一起发送。 when $_POST["syncsts"] line in PHP script executed the following error is thrown.当 PHP 脚本中的 $_POST["syncsts"] 行执行时,抛出以下错误。
10-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
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"}]}
Please tell me what is wrong in the JSON format which I am trying to send to our server which was generated in Java.请告诉我我试图发送到我们用 Java 生成的服务器的 JSON 格式有什么问题。
it looks like the error is at the responce from server. 看起来错误是来自服务器的响应。 the onResponse(JSONObject response)
expects the results to be proper jsonobject. onResponse(JSONObject response)
期望结果为正确的jsonobject。 check if there is any other elements being displayed after echoing the result(such as an error message). 在回显结果之后检查是否还有其他元素正在显示(例如错误消息)。 you can check it from browser using a chrome extension called postman using which you can try sending POST and GET requests manually to server 您可以使用称为postman的chrome扩展程序从浏览器中进行检查,您可以使用该扩展程序尝试将POST和GET请求手动发送到服务器
<?php
// array for JSON response
$response = array();
if (isset($_POST['email']) && isset($_POST['password'])) {
$email= $_POST['email'];
$password= $_POST['password'];
// include db connect class
require_once 'DB_Connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE users SET encrypted_password =
'$password' WHERE email = $email");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["error"] = FALSE;
$response["message"] = "Product successfully updated";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["error"] = TRUE;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["error"] = TRUE;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
------------------------------------------------------------------------
android code
public class ChangePass extends AppCompatActivity {
private static final String TAG = ChangePass.class.getSimpleName();
private Button btn_ChangePass;
private EditText ed_email,ed_pass;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_pass);
btn_ChangePass=(Button)findViewById(R.id.btchangepass);
ed_email=(EditText)findViewById(R.id.email);
ed_pass=(EditText)findViewById(R.id.newpass);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
btn_ChangePass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email=ed_email.getText().toString();
String password=ed_pass.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
// login user
changePassword(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
private void changePassword(final String email,final String password)
{
String tag_string_req = "req_update";
pDialog.setMessage("Updating ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_UPDATE, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error)
{
Intent intent = new Intent(ChangePass.this,
MainActivity.class);
startActivity(intent);
finish();
} else
{
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, "Response Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
---------------------------------------------------------------------
error
org.json.JSONException:
Value <br of type java.lang.String cannot be converted to JSONObject
please help me guys...
this code code is for updating password
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.