Getting ''org.json.JSONArray cannot be converted to JSONObject'' - android

I'm trying to get data from my server in json format in my android application using volley library post json method. But everytime gets a 'org.json.JSONArray cannot be converted to JSONObject'.
This the error:
Error: org.json.JSONException: Value [{"status":"Success","code":1313,"msg":"Request completed successfully"}] of type org.json.JSONArray cannot be converted to JSONObject.
And that's my code:
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("auth", "---------");
jsonObject.put("request", "Login");
jsonObject.put("Name", "raky");
jsonObject.put("Email", "exp#a.com");
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://my.website_name.com/";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("VOLLEY", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR.VOLLEY", error.getMessage());
}
});
jsonObjectRequest.setTag(1);
requestQueue.add(jsonObjectRequest);

The prolem here is that your website response body object is a JSONArray
[
{
"status": "Success",
"code": 1313,
"msg": "Request completed successfully"
}
]
So you get the exception because in the response handler you want a JSONObject and you can't cast a JSONArray to a JSONObject.
What your server (website) have to return to you is a root JSONObject and then in its node tree it could have JSONArray, but the root must be a JSONObject.
So fix your server side code so that it returns:
{
"status": "Success",
"code": 1313,
"msg": "Request completed successfully"
}

Your response is an Array,
you can test your api with some api test tools like Postman and see what you get from api, also you can use StringRequest instead of JsonObjectRequest, by this method you can get any type of response and converted to the type you need

Related

Android Volley Multidimensional JSON Request post Method

How to send multidimensional array on volley post method.
{
"code": "001",
"Emp_id": "0000",
"Exp_Dt": "2021-05-27T00:00:00.000",
"users": [
{
"id": "1087",
"name": "Abhishek Saini",
"email": "info#ezacake.com",
"gender" : "male"
},
{
"id": "1088",
"name": "Gourav",
"email": "gourav9188#gmail.com",
"gender" : "male"
}
]
}
This format I want to call API. Please help
Note - I want to Request with array on my API, not a response
hi you are trying to send a json object there =>
create a parent json object
JSONObject reqJO = new JSONObject();
put other properties eg
reqJo.put("code",0001);
create a user json object
JSONObject user = new JSONObject();
put user properties(if more users loop creating new users)eg
user.put("id",1087)
create a json array of users
JSONArray users = new JSONArray();
add user in users array
users.put(user);
put users array in parent object
reqJO.put("users",users);
Then you continue with your JsonObjectRequest
Here is the answer
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
queue.add(jobReq);

Android Volley ParseError: is there any way to get the actual message from the server?

I am getting the following error from a webapi call in an Android app using volley:
org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
And I want to know how to see the exact message from the server as opposed to the Volley error. Here is the code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof ParseError) {
Log.d(TAG, "onErrorResponse: ParseError: ");
}
}
});
queue.add(request);
It is a really basic call and under most circumstances I get back the jsonobject, but in those cases where the server sends me something different I want to be able to account for it. The error which is thrown is parsing of a value which is not json because it is an error. How can I see what the server is sending from the ErrorListener?

JsonObject within array volley

My Post Data is this,
[
{
"LAT" : "23.04519585271151",
"LONG" : "57.03520084051642"
}
]
my result is this
{"result":"success"}
I am using volley to achieve this post request below is my code,
RequestQueue queue = Volley.newRequestQueue(BottomSheetActivity.this);
JSONObject postparams = new JSONObject();
JSONArray jsonArray = new JSONArray();
postparams.put("LAT", "23.04519585271151");
postparams.put("LONG", "57.03520084051642");
jsonArray.put(postparams);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
url, jsonArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonArrayRequest);
after I am running error block will run why I got error.
I don't know why error only i got give solution to solve this. I am
unfortunately get no result,now also I am trying this help to solve
me this.
Error Log
org.json.JSONException: Value {"message":"success"} of type org.json.JSONObject cannot be converted to JSONArray
What you getting in response is JsonObject. You are trying to convert that into JSONArray and its throwing exception.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
url, jsonArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Above Change JsonArrayRequest to JsonObjectRequest
There are few things I don't understand from the code your were publishing.....
1 - postparams object is never used.....?
2 - Where is the declaration of jsonArray?
Apart from that, I see two problems with the type of :
a) First of all, the data your should be sending (by POST) is a JSONArray, not a JSONObject:
JSONArray postDataJsonArray = new JSONArray();
JSONObject postparams = new JSONObject();
postparams.put("LAT", "23.04519585271151");
postparams.put("LONG", "57.03520084051642");
postDataJsonArray.put(postparams);
b) The response is a JSONObject and not a JSONArray:(In fact, that's the error the log is telling you), so instead of using JsonArrayRequest, use a CustomRequest or a JSONObjectRequest

Send data to server as json format using android Volley

I want to send data from android app to remote server in JSON format.
Below is my json format :-
{
"contacts": [
{
"name": "ritva",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "jisa",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "tithi",
"phone_no": "12345657890",
"user_id": "1"
}
]
}
Can any one tell me how do I send this data using Volley?
Make a volley request like bellow which takes method like POST/GET,
url, response & error listener. And For sending your json override
getBody() method in which pass the json you want to send.
Make a RequestQueue & add the request to it. You might start it by
calling start()
Try this :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this
1. Add Volley and Gson Dependency into build.gradle:
'com.mcxiaoke.volley:library:1.0.19'
'com.google.code.gson:gson:2.7'
Note: If you have JSON data in String variable then just pass the String variable as third parameter in JsonObjectRequest.(Go to Step 6)
If you have JSON data in your classes then just pass the class in gson.toJson() of the third parameter of JsonObjectRequest.(Go to Step 6)
If you want to get the data in class then you need to create classes structure same as JSON data. (Go to step 2)
2. Then create the POJO classes for the above JSON Structure using http://www.jsonschema2pojo.org/
Example Shown in image:
Red marks showing the changes needed to make on site
Then you will get two classes as ContactsTop and Contact.
Note: ContactsTop is name provided at the time of creating POJO classes from jsonschema2pojo.com
3. Add above generated classes into your project
4. Create Volley RequestQueue object and gson object.
RequestQueue requestQueue = Volley.newRequestQueue(this);
Gson gson = new Gson();
5. Then add above JSON data to POJO Classes.
ContactsTop contactsTop=new ContactsTop();
List<Contact> contactList =new ArrayList();
Contact contact=new Contact();
contact.setPhoneNo("12345657890");
contact.setName("ritva");
contact.setUserId("1");
contactList.add(contact);
contactsTop.setContacts(contactList);
6. Create JSONObject to call web service with your data.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "www.your-web-service-url.com/sendContact.php", gson.toJson(contactsTop), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("Volley:Response ", ""+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("Volley:ERROR ", error.getMessage().toString());
}
});
7. Add your jsonObjectRequest into requestQueue. (Don't forget to add this line. this is will add your request in RequestQueue and then only you will get JSON Response or Error from your Service). Don't forget to add INTERNET Permission in AndroidManifest.xml
requestQueue.add(jsonObjectRequest);
Then you will get Response or Error from your Remote Service in android Log monitor.
For sending JSON type data you should make a JSON request using volley
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
Where object is your JSONObject that you want to send. Ask if you want more clarification.
Mark this up if this helps you.

Android Volley POST Json to Server

I am using Volley to transfer the data between Android device and web server.
I found a issue about sending a list of data to the server.
For example, my class will generate the data set like this:
{
"1": {
"1_aID": "5",
"2_aID": "5",
"3_aID": "5",
"4_aID": "5"
},
"2": {
"1_bID": "3",
"2_bID": "3",
"3_bID": "3"
},
"3": {
"1_cID": "4"
}
}
How can i send those data to Server?
I found some tutorial of Post data to server. It must using hashmap.
Any better solution to handle this case?
Make a volley request like bellow which takes method like POST/GET,
url, response & error listener. And For sending your json override
getBody() method in which pass the json you want to send.
Make a RequestQueue & add the request to it. You might start it by
calling start()
Try this :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this
Try this
JSONObject rootObj = new JSONObject();
JSONObject oneObject = new JSONObject();
oneObject.put("1_aID","5");
...
...
JSONObject threeObject = new JSONObject();
oneObject.put("1_cID","4");
rootObj("1",oneObject);
...
...
rootObj("3",threeObject);
new JsonObjectRequest(Request.Method.POST,
url,
rootObj.toString(),
responselistner,
errorlistner);

Categories

Resources