Passing raw JSONObject in POST request in Volley - android

I am using Volley android to POST request to my webservice. Below is the format which I want to post in Body.
// {
// "cust_id": "3",
// "amount": "150",
// "items": [
// {"itemid":"2",
// "qty":"4"},
// {"itemid":"5",
// "qty":"3"},
// {"itemid":"1",
// "qty":"5"}
// ]
// }
items(JSONArray) list is variable. I am using below to pass params
JSONArray jsonArray = new JSONArray();
for (MenuItem m:orderedList) {
JSONObject obj1 = new JSONObject();
obj1.put("itemid", m.getImgid());
obj1.put("qty", m.getQty());
jsonArray.put(obj1);
}
JSONObject obj2 = new JSONObject();
obj2.put("cust_id",cust_id);
obj2.put("amount",totamt);
obj2.put("items",jsonArray);
Log.d("Volley request order",obj2.toString());
JsonObjectRequest req = new JsonObjectRequest(Config.ORDER_URL, obj2, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response is:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error is: ", error.getMessage());
}
});
// Adding request to request queue
LifeCycle.getInstance().addToRequestQueue(req, tag_json_obj);
My Code is working, My Question how do I check complete request body and header as we do in OkHTTp Interceptor.

Your making Json is so sick! Don't use String cut and append to make Json.
Anyway, if you want to know what was you make, you can use this code below
JsonObject json = JsonObject(params);
Log.i("json", json.toString());

Related

How should i get the data from sourceJson in android using volley?

Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.

JSON Array Request Parsing error using Volley Library

I'm working on a news application with api from newsapi.org. I'm using volley library for making JSONArrayRequest and getting data. I'm trying to get my head around json array and json object to understand the parsing. Unfortunately, I'm unable to parse the response. It always calls OnErrorResponse where the response is the json data. Can someone guide me how can I parse the response?
Response:
URL to site:
https://newsapi.org/docs/endpoints/sources
Parsing:
public void jsoncall() {
JsonArrayRequest arrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject;
Log.d("OnResponse", "" + response);
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("sources");
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Toast.makeText(getActivity(), "" + jsonObject1.getString("name"), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this,anime.toString(),Toast.LENGTH_SHORT).show();
lstAnime.add(anime);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "Size of Liste " + String.valueOf(lstAnime.size()), Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), lstAnime.get(1).toString(), Toast.LENGTH_SHORT).show();
setRvadapter(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("OnErrorResponse",""+error.toString());
}
});
requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
requestQueue.add(arrayRequest);
}
dear you are receiving JSONObject include "status" and "sources". I suggest to call JsonObjectRequest
Then parse your response to get JSONArray "sources" :response.getJSONArray("sources");

Parsing Json object received from rest api

I am using Volley library to execute my rest APIs.
Using this I have sent email, password entries to URL and receiving response in JSON as:
{
"success": true,
"data": {
"message": false,
"token": "some token value"
}
}
Now I want to parse the 'token' field received from response and do further action. How can this be parsed?
This is the function where I want to parse the response.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
I have seen this link How to parse JSON Object Android Studio but my "token" field is within another object, so not sure how to do it.
if you want to parse JSON in same manual way you have to do like this to get token.
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("success")== true) {
Toast.makeText(MainActivity.this, "UserExists", Toast.LENGTH_LONG).show();
JSONObject dataObj= jsonObject.getJSONObject("data");
String token= dataObj.getString("token");
////RETRIEVE "token" HERE
} else {
Toast.makeText(MainActivity.this, "User not registered", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is the solution
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject dataObj = response.getObject("data");
String token = dataObj.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
Please use POJO for parsing. Otherwise you will take more time to do this kind of work.
If you are using Volley, why not simply use the JsonObjectRequest:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// parse the response
JSONObject data= response.getObject("data");
String token = data.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
You can try like following.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
JSONObject dataObject = jsonObject.getObject("data");
String token = dataObject.getString("token");
}
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
}catch(JSONException e) {
Log.e("YourTAG","exceptions "+e.toString());
}
Hope it helps you.

How to send sqlite data in the form of JSONObject to MYSQL server with php as backend?

I am using volley for this .
this is my code for fetching data from sqlite .Help me to send this json data to server....Thanks in advance
code : List<ConstTempPlaceorederProduct> contactss = db.getAllContactsPlaceorder();
JSONObject objProduct = new JSONObject();
JSONArray productData = new JSONArray();
for (ConstTempPlaceorederProduct cn : contactss) {
prod_id=cn.getPid();
prod_ref_placeorder_id=cn.getRef_pid();
prod_comp_name=cn.getProd_comp_name();
prod_cat_name=cn.getProd_cat_name();
prod_brand_name=cn.getProd_brand_name();
prod_size=cn.getProd_size();
prod_unit=cn.getProd_unit();
prod_mrp=cn.getProd_mrp();
prod_quantity=cn.getProd_quantity();
prod_name=cn.getProd_name();
prod_total=cn.getProd_total();
JSONObject prodData = new JSONObject();
prodData.put("id", prod_id);
prodData.put("name", prod_brand_name);
productData.put(prodData);
}
objProduct.put("all product", productData);
String result = objProduct.toString();
This is simple sketch. Try this
// Creating the JsonArrayRequest class called arrayreq, passing the required parameters
//JsonURL is the URL to be fetched from
JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,
// The second parameter Listener overrides the method onResponse() and passes
//JSONArray as a parameter
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
// Retrieves first JSON object in outer array
JSONObject jsonResponseObj = response.getJSONObject(0);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array to the request queue
requestQueue.add(productData);
}
}

How can I parse a JSON request using Volley?

I am using the Volley Facebook library to parse the JSON object by passing the String Parameter. But it's throwing JSON exception.
[
{
"error":false,
"newsletter":[
{
"title":"IPS Informa",
"date":"2015-12-02",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello World",
"id":"4",
"post_count":"0"
},
{
"title":"IPS Informa",
"date":"2015-11-30",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello Worl Two",
"id":"1",
"post_count":"6"
}
]
}
]
And here is My Android Code to parse my JSON request:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
JSONObject first = new JSONObject(response);
String err = first.getString("error");
JSONArray second = first.getJSONArray("newsletter");
fisco_tips.clear();
// Parsing json
for (int i = 0; i < second.length(); i++) {
JSONObject obj = second.getJSONObject(i);
FisoTipsSinglton fisco_obj = new FisoTipsSinglton();
//Set Newsletter ID
fisco_obj.setFisco_id(obj.getString("id"));
//Set Title
fisco_obj.setTitle(obj.getString("title"));
//Set Posted Date
fisco_obj.setPosted_date(obj.getString("date"));
//Set Posted By
fisco_obj.setPosted_by(obj.getString("posted_by"));
//Set Image URL
fisco_obj.setThumbnailUrl(obj.getString("image"));
//Set Short Description
fisco_obj.setShort_description(obj.getString("description"));
fisco_obj.setPost_count(obj.getString("post_count"));
fisco_tips.add(fisco_obj);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Json Error", "Here is error: " + e.toString());
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("country", country);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, related_posts);
}
How can I read my JSON object using string request in Android Volley library?
The error message that you're getting:
type org.json.JSONArray cannot be converted to JSONObject
indicates that you're trying to convert a JSONArray to a JSONObject. This happens in the first line of code in your try block.
JSONObject first = new JSONObject(response);
You're passing the entire response to the JSONObject constructor, but the response is wrapped in [ ], so it's a JSONArray, not a JSONObject. Your first step should be to parse the response as a JSONArray, get the JSONObject from the first element of the array, then continue parsing.
try {
JSONArray wrapper = new JSONArray(response);
JSONObject first = (JSONObject)wrapper.get(0);
boolean err = first.getBoolean("error");
JSONArray newsletters = first.getJSONArray("newsletter");
// Parsing json
for (int i = 0; i < newsletters.length(); i++) {
JSONObject news = newsletters.getJSONObject(i);
.
.
.
}
} catch (JSONException e) {
Log.d("MainActivity.java", e.toString());
}
If there's a chance that your data source might return an empty array, you should do more error checking than I've shown here.
String err = first.getString("error");
Should be:
Boolean err = first.getBoolean("error");
Plus what Bill the Lizard said.
Instead of using Volley check OkHTTP with Retrofit. It will wrap responses automatically ;)

Categories

Resources