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 ;)
Related
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.
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");
I have a RESTful API running in my local machine which returns a response in JSON (Actually this JSON is the response of nodejs Soap client request) depending on the request. For this particular case I receive POST request from an Android client and return the following response:
{
QueryAcctBalResponse: {
BalExDtoList: {
BalExDto: [{
BalID: "xxxx",
AcctResID: "xxxx",
AcctResName: "xxxx",
BalType: "xxxx",
Balance: "xxxx",
EffDate: "xxxx",
ExpDate: "xxxx",
UpdateDate: "xxxx"
}, {
BalID: "yyyy",
AcctResID: "yyyy",
AcctResName: "yyyy",
BalType: "yyyy",
Balance: "yyyy",
EffDate: "yyyy",
ExpDate: "yyyy",
UpdateDate: "yyyy"
}]
}
}
}
The problem is each time I try to parse that response and display this information in android (Particularly "AcctResName"). I get org.json.JSONException: No value for BalExDto. I use Volley Libray in android to parse Json and i used Jsonobject request.
Request Code.
JsonObjectRequest sq = new JsonObjectRequest(Request.Method.POST, balanceUrl, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("BalExDto");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
Toast.makeText(CheckBalance.this, ""+jsonObject.get("AcctResName"), Toast.LENGTH_LONG).show();
}
pd.hide();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", "Response_TAG: "+response);
}
It's because you don't have a JSON Array, you have a JSON Object.
First of all, you need to get the JSON object from your API response,
JSONObject jsonObject = response.getJSONObject("QueryAcctBalResponse")
and inside that JSON object is the JSON Array.
JSONArray jsonArray = response.getJSONArray("BalExDtoList");
The error says - you are parsing BalExDto wrong. BalExDto is not direct child of response. So you have to parse QueryAcctBalResponse and BalExDtoList and then you can get BalExDto. Because BalExDto is inside BalExDtoList and BalExDtoList is inside QueryAcctBalResponse.
JsonObjectRequest sq = new JsonObjectRequest(Request.Method.POST, balanceUrl, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject queryAcctBalResponse = response.getJSONObject("QueryAcctBalResponse");
JSONObject balExDtoList = queryAcctBalResponse.getJSONObject("BalExDtoList");
JSONArray jsonArray = balExDtoList.getJSONArray("BalExDto");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
Toast.makeText(CheckBalance.this, ""+jsonObject.get("AcctResName"), Toast.LENGTH_LONG).show();
}
pd.hide();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", "Response_TAG: "+response);
}
BalExDto array is not the direct child of the response. It is inside BalExDtoList which is inside QueryAcctBalResponseobject. You can not directly access any node in the JSON, you need to traverse the full path before you could access them.
You need to get the array like below
JSONObject queryAcctBalResponse = response.getJSONObject("QueryAcctBalResponse");
JSONObject balExDtoList = queryAcctBalResponse.getJSONObject("BalExDtoList");
JSONArray jsonArray = balExDtoList.getJSONArray("BalExDto");
I am trying to parse an array that I have retrieved from my flask server. The array is as follows.
"[{\"firstName\": \"Roy\", \"lastName\": \"Augustine\"}]"
I am parsing the array in Android studio using the following code.
private void loadDrives() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://142.93.216.24:5000/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
//adding the product to product list
driveList.add(new TestMl(
jsonObject.getString("firstName"),
jsonObject.getString("lastName")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
I am however getting the following error.
org.json.JSONException: Value [{"firstName": "Roy", "lastName": "Augustine"}] of type java.lang.String cannot be converted to JSONObject
The error suggests that the json is being successfully retrieved, but it cannot parse the array successfully. Could anybody suggest a suitable solution?
YOu're fetch data using wrong name.. it is lastName not lastname
Change this
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
To
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));
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());