JsonObject within array volley - android

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

Related

How to send a list of integers as a request body in android using volley?

My Restful API expect a list of integer arrays. The API works fine when I use postman client to send an json array like so [1,3,4].
I am using android volley to make requests. I have a list of integers which I want to send to the API like this.
//converting integer array to a json array
JSONArray myIntegerJsonArray = new JSONArray(myIntegerArray);
String url = "myurl...";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, myIntegerJsonArray, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//... do stuff here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingletonRequestQueue.getInstance(this).addToRequestQueue(request);
I am currently getting HttpMessageNotReadableException: Required request body is missing error. So I am guessing it's not sending the myIntegerJsonArray for some reason. What am I doing wrong?

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

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

Android Json parsing string cannot be converted to json object error

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/

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.

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

Categories

Resources