Android Json parsing string cannot be converted to json object error - android

I want to send parameters such as username and password.
I got an error like String cannot be converted to jsonobject.
I dont know what this happening.Anyone pls help me my code is:
JSONObject obj=new JSONObject();
try{
obj.put("username","test");
obj.put("password","test");
} catch (JSONException e) {
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
}

There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.

It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)
======================
This doesn't answer your question, but this will help you tremendously and make your life easier.
Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.
https://github.com/google/gson
http://square.github.io/retrofit/

Related

Android Volley onResponse function not running

Here is my function which I filled in from https://developer.android.com/training/volley/request#java
String url = "http://192.168.1.31:8000/api/social/convert-token";
JSONObject jsonBody = new JSONObject();
try{
jsonBody.put("grant_type", "convert_token");
jsonBody.put("client_id", clientID);
jsonBody.put("client_secret",clientSecret);
jsonBody.put("backend", "facebook");
jsonBody.put("token", facebookAccessToken);
jsonBody.put("user_type", userType);
}catch (JSONException e){
e.printStackTrace();;
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Execute Code
Log.d("LOGIN TO SERVER", response.toString());
// Save server token to local DB
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString("token", response.getString("access_token"));
}catch (JSONException e){
e.printStackTrace();
}
editor.commit();
//Start home activity
startActivity(new Intent(Login.this,Home.class));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
The string URL is my Django server, this works properly, I can access it from the web browser on the android phone.
The next block of just converts data I previously got into JSON format. I tested this by copying and pasting the URL, and each parameter in Postman, and it works and returns JSON back.
jsonBody is then passed into the Json Request, along with the URL. The Log.d "LOGIN TO SERVER", is not visible in my log. So I know that the onResponse does not run. Further I put a Log line in the onErrorResponse, and it was visible in my log.
So onReponse does not run, while onError response does. I don't know what the error is.
Three cases,
Check if there are any headers to pass using getHeaders().
2.As it is http and not https, provide android:usesCleartextTraffic="true" in manifest inside . It allows you to access http urls also.
3.You said you have kept logger in Response.onErrorListener(){} and what is the error. If not give it by Log.d("Error", "Error getting "+error.toString);

How to properly format a POST API request with JSON?

I have teaching myself how to develop Android applications and I recently started using the Volley library for networking. I have been able to send basic requests with it. I was experimenting with Pocket's API to see if my app could fetch the items. Their documentation page mentions that I have to send a JSON request like so
POST /v3/oauth/request HTTP/1.1
Host: getpocket.com
Content-Type: application/json; charset=UTF-8
X-Accept: application/json
{"consumer_key":"1234-abcd1234abcd1234abcd1234",
"redirect_uri":"pocketapp1234:authorizationFinished"}
So I made a JSONObject in my app, added the key consumer_key with the value of my consumer key, then added in the key redirect_uri with its respective value. I sent this JSONObject as a request to the required URL as a POST request using Volley. The response code I received was 403, which is caused by a bad consumer key. I have double-checked the consumer key, so the problem lies with my request. How should I go about making the JSON request? Do I have to add the extra data, like Content-Type? If so, how?
If it is not too much, could you point me to a beginner-friendly resource on JSON, since I do not have much knowledge about web development?
Thank you.
What request methode do you use on your code? I am facing issue when using StringRequest method. Its work when use JsonObjectRequest method.
Here is how to create request besides on my experience.
Create Header Parameter
final Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("X-Accept", "application/json");
headers.put("consumer_key", "your-consumer-key");
headers.put("redirect_uri", "https://kamus.nusagates.com");
Create JSONObject From headers
JSONObject obj = new JSONObject(headers);
Create JsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://getpocket.com/v3/oauth/request", obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//get all response data
Log.d("respon", String.valueOf(response));
try {
//get code from response
Log.d("respon code", response.getString("code"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
String server = String.valueOf(response.headers);
Log.d("header", server);
return super.parseNetworkResponse(response);
}
};
Add the request to The Queue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(jsonObjectRequest);
May this could help you solve your problem.
Cheers

Using Volley without Gson

Today I got to know that Retrofit uses gson(or any other convertor) to serialize or deserialize the json response (response that was got using okhttp or any related library).
Now, when I was naive(in some sense still am) and I used to use Volley and at that time I never used Gson or any related library and same for okhttp.But i used to get my response and inflate it successfully on my views.
1. Now does Volley internally do what Retrofit does using Gson and Okhttp?
If not? 2. Then how did i able to get values parsed without using anything?
Below is the sample Codes that i used to write:-
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(
Request.Method.POST, URL_THUMB, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray=response.getJSONArray("server_response");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=(JSONObject)jsonArray.get(i);
String id=jsonObject.getString("id");
String artist_name=jsonObject.getString("artist_name");
String img_id=jsonObject.getString("img_id");
listId.add(id);
listArtistName.add(artist_name);
listImgID.add(img_id);
}
recyclerView.setAdapter(comedy_adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
and now just inflate these list values to my views.
Where did I go wrong? (I don't think I was wrong as things went well and code always run fine)
In your example you're parsing the response into JSON arrays and objects manually. Converters such as Gson let you parse the response into a variable of a custom object in a single line.
For example, if I have the following model:
public class Model {
private int id;
private String name;
}
I can parse a string response using the following code:
Model model = gson.fromJson(str, Model.class);
Otherwise, you have to do it manually, like what you're doing at the moment:
JSONObject jsonObject = response.getJSONObject("str");
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
Model model = new Model(id, name);
In Retrofit 2 you don't even have to call fromJson - you simple receive the object you expect as an input parameter in onResponse. It's very useful when dealing with more complex models.

Unable to parse integer from Volley response

I want to get the count of the documents in remote mongodb database. For that I am using custom query url. The url only returns an integer instead of a JSON packet. I am using Volley in android to make this query. The following code gives Error: E/Errorīš• com.android.volley.ParseError: org.json.JSONException: Value 2 of type java.lang.Integer cannot be converted to JSONObject
JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("onResponse", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error",volleyError.toString() );
}
});
The request made using the url in a browser gives the following result.
It's not a JSON Request Use String request so it will return the response as a 2.
so simple you can get this using
int value = yourjsonobject.getInt("key");
If it helps please let me know

Convert JSON String to Dictionary in Android

I have the following json formatted string that is returned from the web service:
{"Success":false,"Message":"This version is not supported"}
I am using the following code to invoke the web service:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mywebsite/check/getcompatibilityinfo", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
The response contains the json string now I need to access the Success and the Message property. Is there any simple way to do it without using complicated third party libraries?
The JSONObject class is already available in your Android codebase (no 3rd party dependencies). Since your example uses normal (simple) JSON, you can use:
try {
JSONObject responseJSON = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
boolean success = responseJSON.getBoolean("Success");
String message = responseJSON.getString("Message");

Categories

Resources