I can’t find answer. tried many websites including this. i want to know where from the problem coming.
Error is: org.json.JSONException: Value connection of type java.lang.String cannot be converted to JSONObject
This is my andorid code:-
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String success=jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i=0;i<jsonArray.length();i++) {
JSONObject object=jsonArray.getJSONObject(i);
String uname=object.getString("username").trim();
String email=object.getString("email");
Toast.makeText(MainActivity.this, "Login Successful!!! n Your Name: "+uname+"nYour Email: "+email, Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this," Error!!"+e.toString(),Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
signin_btn.setVisibility(View.VISIBLE);
}
}
},
Logcat
2019-09-06 19:40:37.264 7944-7944/com.example.project W/System.err:
org.json.JSONException: Value connection of type java.lang.String
cannot be converted to JSONObject 2019-09-06 19:40:37.264
7944-7944/com.example.project W/System.err: at
org.json.JSON.typeMismatch(JSON.java:111) 2019-09-06 19:40:37.264
7944-7944/com.example.project W/System.err: at
org.json.JSONObject.(JSONObject.java:160) 2019-09-06
19:40:37.264 7944-7944/com.example.project W/System.err: at
org.json.JSONObject.(JSONObject.java:173)
3
Answers
As the exception implies, the
response
String cannot be converted to aJSONObject
:from: http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
Ensure your
response
String (obtained from a POST request toURL_LOGIN
) is indeed a valid JSON string. Either write an end-to-end test incorporating the system hostingURL_LOGIN
or manually test with a client such as Postman that the system servingURL_LOGIN
works as intended given the request from your application.Your Retrofit callback response listener will be Response type of Retrofit.
Make your code like this and it will work fine.
L
when I use these statements my code doesn’t show a problem
but when I don’t use it work correctly: