Value <Br of Type Java.Lang.String Cannot Be Converted to JSONobject on Android

org.json.JSONException: Value br of type java.lang.String cannot be converted to JSONObject

Thanks I manage to correct some of the errors 2 ';' were missing and I could see the error with Log.i("tagconvertstr", "["+result+"]");

The msg that it is showing is something like that :

[<br/ > font size = 1 table class=''xdebug-erroe' dir='ltr' ... loads of html code that wasn't in my initial code then....{"message":"Problem sending you the activation mail !"}]

So there's a problem with the json format on that message "Problem sending you the activation mail" but the user was registered OK!

So the second time i would try that code it would show me in a correct json format : "This email has already been used" ! (without any errors) but i still can't find the error in my php code : S

Value br of type java.lang.String cannot be converted to JSONObject - Android Studio

I found the solution, the problem really was because of the format of the key and signature.

Android Studio:

KeyStore ks = null;
byte[] signature = null;
try {
ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);

KeyStore.Entry entry = ks.getEntry(alias, null);
if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
Log.w("DEBUG_EC", "Not an instance of a PrivateKeyEntry");
}
Signature s = Signature.getInstance("SHA256withECDSA");
s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey());
s.update(data.getBytes());
signature = s.sign();
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | UnrecoverableEntryException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
}

JSONObject object2 = new JSONObject();
try {
object2.put("id", data);
object2.put("key", key);
object2.put("signature", Base64.getEncoder().encodeToString(signature));
} catch (Exception e) {
Log.d("ID_DEBUG","Error");
e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.POST, url, object2, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("ID_DEBUG","String Response : "+ response.toString());

try {
String resultados = response.getString("result_text");

if(resultados.equals("missing parameters")){
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Sucess!", Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
Log.d("ID_DEBUG","Error");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
Log.e("ID_DEBUG", error.toString());
}
});

queue.add(jsonObjectRequest2);

PHP:

<?php
function json_response($message = null, $code = 200) {
// clear the old headers
header_remove();
// set the actual code
http_response_code($code);
// set the header to make sure cache is forced
header("Cache-Control: no-cache, no-store");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
// treat this as json
header('Content-Type: application/json');
$status = array(
200 => '200 OK',
400 => '400 Bad Request',
422 => 'Unprocessable Entity',
500 => '500 Internal Server Error'
);
// ok, validation error, or failure
header('Status: '.$status[$code]);
// return the encoded json
return json_encode($message,JSON_UNESCAPED_SLASHES);
}

if (empty($_POST)) {
$_POST = json_decode(file_get_contents("php://input"), true) ? : [];
}

(some code ...)

$res = array();

if(empty($_POST['key']) || empty($_POST['signature'])) {
$res['result_code']=400;
$res['result_text']='missing parameters';
echo json_response($res);
} else {
$key=$_POST['key'];
$signature=$_POST['signature'];

$key = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($chave, 64, "\n") . '-----END PUBLIC KEY-----';
$key = openssl_pkey_get_public($key);
if ($key == false) {
$res['result_code']=400;
$res['result_text']='key error';
echo json_response($res);
}

// state whether signature is okay or not
$ok = openssl_verify($data, base64_decode($signature), $key, OPENSSL_ALGO_SHA256);
if ($ok == 1) {
if($key != NULL || $signature != NULL){

(some code ...)

$final_result = array();
$final_result['result_code']='200';
$final_result['result_text']='OK';
echo json_response($final_result);
}

} elseif ($ok == 0) {
$res['result_code']=400;
$res['result_text']='invalid signature';
echo json_response($res);
} else {
$res['result_code']=400;
$res['result_text']='error checking signature';
echo json_response($res);
}

// free the key from memory
openssl_free_key($pubkeyid);
}
}

?>

Thank you to everyone who tried to help!

value br of type java.lang.String cannot be converted to JSONObject In Android Programming

Search a lot and find a way

$user=$_REQUEST['user'];

Php change to

$user=$_REQUEST['username'];

Will work Perfectly..

Thanks to Yazen

https://stackoverflow.com/users/3604083/yazan

JSONException: Value br of type java.lang.String cannot be converted to JSONArray

You do not return a valid JSON, seems that you are returning a HTML snippet with <br>
have a look at your returning source of your website.

What should i do? The Php code runs on web page without any errors but why got an error in this part? In logcat also has: ( ! ) Notice: Undefined variable: user_id in C:\wamp\www\getProducts.php on line 27

So the user_id is not defined! Just look at your GET/POST Parameters or show us your relevant php code.

Please use echo json_encode($output); not print.

And what are you doing if there is no returning row from your first Query.
Try this.

$sql=mysql_query("SELECT user_id FROM users WHERE user_name='".$user_name."' AND user_pass='".$password."' "); 
if(mysql_num_rows($sql) == 0){
echo "USERID CANNOT BE FOUND";
}
while($row=mysql_fetch_array($sql)) {
echo "USERID FOUND" .$row["user_id"] ;
$user_id=$row["user_id"];
}

It seems that user_name could not be found. So just debug it there by trying to echo your user_id after the while. If you do not get the UserID FOUND echo the user_name and password do not exist.

Edit: As your logact says, there is no Entry for the username you are passing so the $user_id will never be filled.

http://192.168.2.245/getProducts.php?login=1&user_name=UserName&password=Password

You are passing user_name = UserName and password = Password. Does this entry really exist in your Database?

Also for better performance have a look at MySQL LETF JOIN and MySQL subqueries.

Value br of type java.lang.String cannot be converted to JSONObject on android

About your HTML

You're trying to get rid of some HTML code that actually tells you there is an error. Here is what it looks like:

interpreted HTML response

Maybe if you solve that problem, your JSON issue will vanish on its own, because you won't have HTML stuff before your JSON.


Earlier part of the response

I guess you are getting your exception at this line (please tell me if I'm wrong):

jsonResponse = new JSONObject(Content);

If you want to know what's wrong with the parsing of Content, you might want to log that string and see how it looks.

Apparently, Content is HTML code (It contains some <br, according to the exception) instead of a proper JSON String. Take a look at where you get this string from, this is probably your problem.


UPDATE:

OK, according to what you posted, your Content string contains the JSON string (the one surrounded by braces {}) but it also contains an HTML part, which needs to be removed.

Put this code before you try to create the JSONObject:

int jsonStart = Content.indexOf("{");
int jsonEnd = Content.lastIndexOf("}");

if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) {
Content = Content.substring(jsonStart, jsonEnd + 1);
} else {
// deal with the absence of JSON content here
}

UPDATE 2:

The previous code snippet does not seem sufficient because your HTML contains braces ({}). If the server always returns that kind of HTML, you might want to just get rid of the font tag before running the previous snippet:

Content = Content.replaceFirst("<font>.*?</font>", "");

WARNING: This is very sketchy, and answers only this very particular issue. It won't work with every possible server response.

You should have a look at other questions regarding the removal of HTML from a String in Java, for more complete answers.



Related Topics



Leave a reply



Submit