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.
Related
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.
On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);
I have a JSON that retrieves all the users of a database. To simplify, I will show the first two users:
[
{
"id":"1",
"name":"Peter",
"age":"25"
},
{
"id":"2",
"name":"Andrew",
"age":"32"
},
...
]
As you can see, it is an array without name that contains some JSONObjects so I have tried to retrieve these data from Android with Volley library going through the whole array but without success.
Here is the code that I have by the moment:
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
if (response != null) {
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
queue.add(jsonArrayRequest);
It always gives to me the following error:
Unhandled exception: org.json.JSONException
I also tried to retrieve the JSONArray before trying to retrieve the JSONObject but it does not allowed me because the method
JSONArray json = response.getJSONArray(0);
also gave to me the same error that I have pointed before.
I looked for a lot of examples and I cannot see where my problem is.
What am I doing wrong?
Thanks in advance!
You are not handling JSONException.
Give this a try.
StringRequest request = new StringRequest(Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Cannot resolve constructor 'JsonArrayRequest(int, java.lang.String, anonymous com.android.volley.Response.Listener<org.json.JSONArray>, anonymous com.android.volley.Response.ErrorListener)'
Error doesn't lie. That request doesn't accept a Method type.
JsonArrayRequest(
String url,
Response.Listener<JSONArray> listener,
Response.ErrorListener errorListener)
StringRequest, on the other hand, does.
StringRequest(
int method,
String url,
Response.Listener<String> listener,
Response.ErrorListener errorListener)
Regarding,
Unhandled exception: org.json.JSONException
response.getJSONObject will throw that exception, so you must use a try-catch.
if (response != null) {
try {
for (int i = 0; ...) {
JSONObject jo = response.getJSONObject(i);
// use 'jo'
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You should add final in final JsonArrayRequest
GOOD LUCK !!
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,null, new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
try{
if (response != null) {
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
String tieude = obj.getString("tieudetin");
Toast.makeText(test.this,tieude,Toast.LENGTH_SHORT).show();
//txt.setText(tieude+"");
}
}
}catch(Exception e){
e.getMessage();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonArrayRequest);
Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...
public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");
//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");
res.success = success;
res.data = data;
completion.onCompletion(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Use StringRequest
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO something
}
});
Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:
try {
JSONObject object = new JSONObject(value);
}
catch (JSONException) {
//if it throws, "value" contains not a JSONObject
JSONArray array = new JSONArray(value);
}
After going through the API I found a simple solution.
Since you are not sure of the return type, follow mentioned below steps.
First:
JSONArray arrayInstance = new JSONArray();// declare array instance to handle both the cases
Object objectInstance = rootObject.get(key); //key is the response string holding the value either jsonArray or jsonObject
Second:
if(objectInstance instanceof JSONArray){
arrayInstance = rootObject.getJSONArray(key);
}
else{
JSONObject tempObject = rootObject.getJSONObject(key);
arrayInstance.put(tempObject);
}
Third:
You can iterate though the array for the desired processing.
I got this error from volley library
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
the error
com.android.volley.ParseError: org.json.JSONException: Value [{"id":"admin","name":"Admin"}] of type org.json.JSONArray cannot be converted to JSONObject
How can I receive the result as string and then I will process it using jackson ?
If you want to receive the result as a string don't use the JSONRequest. Go with the simple Request class.
Your problem is pretty simple the server is giving back a JSONArray with just one element inside.
A JSONArray is not a JSONObject. That's why the parsing is failing.
We Have to use JsonArrayRequest instead of JsonObjectRequest. The code as:
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://192.168.88.253/mybazar/get_product_list.php";
// prepare the Request
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
Hope, it's solve the problem.
I noticed that there is class JsonArrayRequest supported by volley so I use this class and the problem solved, I was using JsonObjectRequest
https://android.googlesource.com/platform/frameworks/volley/+/43950676303ff68b23a8b469d6a534ccd1e08cfc/src/com/android/volley/toolbox
Probably the below logic will work for you:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject1 = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("statewise");
Log.d("Json response", "onResponse: "+jsonObject1.toString());
for (int i = 0; i < jsonArray.length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Here you will get your result so can use textview
//to populate the result
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: "+error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}