简体   繁体   中英

Volley's JsonObjectRequest gives "org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject" exception

Expected JSON to be send to server

{"syncsts":
          [
          {"status":"1","Id":"9"},
          {"status":"1","Id":"8"}
          ]
}

Expected way of retrieval of JSON Object on the server

$arr = $_POST['syncsts']

(I think )

$arr should have [{"status":"1","Id":"9"},{"status":"1","Id":"8"}]

Volley JsonObjectRequest Function along with JSON style parameter

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 script

/**
* 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. when $_POST["syncsts"] line in PHP script executed the following error is thrown.

JSONObject toString() and the Error as shown in the logcat

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

PHP script to show what is received on server (Debugging)

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);

test.txt

{"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.

it looks like the error is at the responce from server. the onResponse(JSONObject response) expects the results to be proper 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

<?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM