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);
Related
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
I have a question about converting from a custom JSON response to WordPress standard JSON response for WP V2 API.
My custom json response looks like this - it's framed within
{
"categories":
[26]
0:
{
"term_id": 12
"name": "Android"
"slug": "android"
"term_group": 0
"term_taxonomy_id": 12
"taxonomy": "category"
"description": ""
"parent": 463
"count": 10
"filter": "raw"
"cat_ID": 12
"category_count": 10
"category_description": ""
"cat_name": "Android"
"category_nicename": "android"
"category_parent": 463
}
}
My code looks like this
// Preparing volley's json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<Category> categories = new ArrayList<Category>();
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}else {
// Parsing the json response
JSONArray entry = response.getJSONArray(TAG_CATEGORIES);
// loop through categories and add them to
// list
for (int i = 0; i < entry.length(); i++) {
JSONObject catObj = (JSONObject) entry.get(i);
// album id
String catID = catObj.getString(TAG_TERM_ID);
// album title
String catTitle = catObj.getString(TAG_TERM_NAME);
Category category = new Category();
category.setId(catID);
category.setTitle(catTitle);
// add album to list
categories.add(category);
}
The WordPress RST API V2 the JSON response looks like this:
[10]
0: {
"id": 12
"count": 10
"description": ""
"link": "https://torbjornzetterlund.com/category/technology/mobile-apps/android/"
"name": "Android"
"slug": "android"
"taxonomy": "category"
"parent": 463
"img": false
"_links": {
"self": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories/12"
}-
- "collection": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories"
}-
- "about": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/taxonomies/category"
}-
- "up": [1]
0: {
"embeddable": true
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories/463"
}-
-"wp:post_type": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/posts?categories=12"
}-
- "curies": [1]
0: {
"name": "wp"
"href": "https://api.w.org/{rel}"
"templated": true
}
}
}
}
The new JSO response do not have a category called categories, so I can not use this statement.
// Parsing the json response
JSONArray entry = response.getJSONArray(TAG_CATEGORIES);
I can not find any good documentation for the volley library or examples, my current code gets an object from the url, then the code uses the response.getJSONArray to get the array from the object.
What do I need to do if I can not identify the Array within the object, the json response I get is an array, should I change the request from object to array. I'm not sure a bit lost on this one. Appreciate any help.
You are using an JsonObjectRequest, what was right for your api but now it comes an JsonArray from your api.
There is also a JsonArrayRequest in the Volley Toolbox. If you change the Request Type then it will work.
If something is not clear, feel free to ask.
This is how my code snippet looks like after the change from JsonObjectRequest to JsonArrayRequest
JsonArrayRequest jsonArrReq = new JsonArrayRequest(url, new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
List<Category> categories = new ArrayList<Category>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject catObj = response.getJSONObject(i);
// album id
String catID = catObj.getString(TAG_TERM_ID);
// album title
String catTitle = catObj.getString(TAG_TERM_NAME);
Category category = new Category();
category.setId(catID);
category.setTitle(catTitle);
// add album to list
categories.add(category);
// Store categories in shared pref
AppController.getInstance().getPrefManger().storeCategories(categories);
// String the main activity
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
First I need to check the json object status 400 if status 400 to get the image otherwise it shows error. I don't how to check status in JSON empty object in android volley. and also I need some help on how to get image by using banner path and banner name.
My Json
{
"status": "200",
"requestType": "bannerImages",
"basePath": "http:\/\/192.168.0.33\/cartwebsite3\/",
"bannerPath": "http:\/\/192.168.0.33\/cartwebsite3\/cdn-images\/banner\/",
"response": {
"data": [
{
"banner_id": "37",
"banner_name": "1457324300894ac3df08bd3648452703d8412f82c2.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324300"
},
{
"banner_id": "36",
"banner_name": "14573242986be953c24858a3c2d787d57e6b77be1f.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324298"
},
{
"banner_id": "35",
"banner_name": "1457324295f8d8153fb4f29d3af15276db22435d48.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324295"
}
]
},
"request": {
"postData": [],
"getData": {
"type": "bannerImages",
"result": "json"
}
}
}
Thank in Advance
If you just want to get status, try like this:
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if you want to parse whole data, I would recommend you to use Gson.
For easy JSON parsing/manipulating/etc use GSON library at android. Example you can make custom objects and straight create new instance of your custom object from parsing and then just check fields or whatever you need to do.
CustomObject object= gson.fromJson(JSON, CustomObject.class);
if(object.bannerPath != null) {
//Do something
}
Here is the GSON in Github
and here for GSON tutorial
//editing Rohit Arya Code little bit
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if(status.equalIgnorecase("400")){
try {
JSONObject jsonObject=new JSONObject("yourResponse");
jsonObject1=jsonObject.getJSONObject("response");
JSONArray jsonArray=jsonObject1.getJSONArray("data");
JSONObject jsonObject2;
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
String banner_name=c.getString("banner_name");
Log.e("banner_name",banner_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
// don't download
}
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);
Android Json Api Key Nested how to use ?MsgID ,UsrID Repeat how to call? Volley
I have a json which has a number of nested JSONARRAY.
{
"status": "success",
"data": {
"2547": {
"MsgID": "2547",
"UsrID": "352",
"MsgID": "221",
"ThroughUsrID": null,
"MsgID": "1",
"MsgDt": "2016-03-22 11:55:13",
"buscard": {
"UsrID": "221",
"EntID": "7",
"EntID": "1",
"UsrFavorites": 0,
"UsrLinkSts": "connected"
},
}
}
I think you are trying to parse Json data. Try to do something like this:
try {
JSONObject jsonObject = new JSONObject(stringToParse);
JSONObject data = jsonObject.optJSONObject("data");
JSONObject tempData = data.optJSONObject("2547");
String msgID = tempData.optString("MsgID");
// Similarly parse other info
JSONObject busCard = tempData.optJSONObject("buscard");
//Again parse required data from busCard
} catch (JSONException e) {
e.printStackTrace();
}