JSON Object cannot be converted to JSONArray Search App - android

i´d like to create a search for my Android app but when I try to I just get the JSON Value along with ...JSON Object cannot be converted to JSONArray. Btw I am using Volley.
Code Sample for getting JSON:
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, R.string.i_enter_request, Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,getString(R.string.d_wait),getString(R.string.d_fetch),false,false);
String url = AppConfig.DATA_URL+editTextId.getText().toString().trim();
JsonArrayRequest searchReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_LONG).show();
loading.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject pObj = response.getJSONObject(i);
Products item = new Products();
item.setTitle(pObj.getString("name"));
ProductItems.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
loading.dismiss();
}
});
AppController.getInstance().addToRequestQueue(searchReq);
}
And the JSON itself by searching for "1":
{
products: [
{
id: "1",
name: "Test",
price: "123",
item_desc: "Its a Test"
}],
success: 1
}
It would be great if someone could help me with it.
Thanks

This is not a JSONArray:
{products:[{id: "1", name: "Test", price: "123", item_desc: "Its a Test" } ], success: 1 }
So you're getting an error because your callback tries passing it in as a JSONArray You need to change your callback to:
#Override
public void onResponse(JSONObject response) {}
And then you need to parse the response as a JSONObject, not a JSONArray.

Related

How to implement Nested JsonObject /JsonArrey in One Json Value?

I have a Json Format
Json Url
http://inter.youdao.com/intersearch?tag=simple-eh&from=en&to=hi&q=spin
I need only first i
first i - n. घुमाव; चक्रण; झुकाव
second i. v. घूमना; कातना
Is it possible that first i + second i word only first word = n. घुमाव, v. घूमना
The problem was showing result in android no eh velue.
How to get hindi word.
Json Result
{
"data": {
"eh": {
"": "spɪn",
"ukphone": "spɪn",
"ukspeech": "spin&type=1",
"trs": [
{
"i": "n. घुमाव; चक्रण; झुकाव"
},
{
"i": "v. घूमना; कातना"
}
],
Android Implement :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() { #Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
JSONObject result = response.getJSONObject("data");
String eh= result.getString("eh");
JSONObject result1 = response.getJSONObject("eh");
String hindi= result1.getString("trs");
jsonResponse = "";
jsonResponse += "Hindi: " + hindi ;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
finally fix the Problem
Thanks
here is code :
try {
// Parsing json object response
// response will be a json object
String syncresponse = response.getString("data");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("eh");
JSONObject object3 = new JSONObject(synckey);
JSONArray jArray1 = object3.getJSONArray("trs");
for(int i = 0; i < jArray1 .length(); i++)
{
JSONObject object4 = jArray1.getJSONObject(i);
String comp_id = object4.getString("i");
String replace = object4.getString( "i" ).replace( ";", "," );
translate.setText(mWord + "=" + comp_id);
}

Volley JSON Exception with Bing Search API

I have implementing Bing Images Search API with Volley I need to request for the JSONArray values to request all the thumbnail urls. Here is the JSON format for the Bing Image Search:
[
{
"_type":"Images",
"instrumentation":{
},
"readLink":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/images\/search?q=puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=puppies&FORM=OIIARP",
"totalEstimatedMatches":995,
"nextOffset":37,
"value":[
{
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&simid=608039673288263152",
"name":"Cute Golden Retriever Puppies Photos ~ Cute Puppies Pictures, Puppy Photos",
"thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.sa4AFBPcfVJbIx1MEkakmgHaFj&pid=Api",
"datePublished":"2018-02-04T22:46:00.0000000Z",
"contentUrl":"http:\/\/1.bp.blogspot.com\/-NnDHYuLcDbE\/ToJ6Rd6Dl5I\/AAAAAAAACa4\/NzFAKfIV_CQ\/s1600\/golden_retriever_puppies.jpg",
"hostPageUrl":"http:\/\/puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies-photos.html",
"contentSize":"376369 B",
"encodingFormat":"jpeg",
"hostPageDisplayUrl":"puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies...",
"width":1600,
"height":1200,
"thumbnail":{
"width":474,
"height":355
},
"imageInsightsToken":"ccid_sa4AFBPc*mid_01FB7631BE5F833B1851922E2AE55143A9DDA195*simid_608039673288263152*thid_OIP.sa4AFBPcfVJbIx1MEkakmgHaFj",
"insightsMetadata":{
"recipeSourcesCount":0,
"bestRepresentativeQuery":{
"text":"Cute Golden Retriever Puppies",
"displayText":"Cute Golden Retriever Puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Cute+Golden+Retriever+Puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&FORM=IDBQDM"
},
"pagesIncludingCount":1238,
"availableSizesCount":240
},
"imageId":"01FB7631BE5F833B1851922E2AE55143A9DDA195",
"accentColor":"AA6F21"
}
]
}
]
This is my Volley Request for JSON Array.
private void requestedTrendingImages(String url) {
Log.d("Query URL: ", url);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject images = response.getJSONObject(i);
jsonResponse = images.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
HolaApp.getInstance().addToRequestQueue(jsonArrayRequest);
}
My String URL is correct I am new to Volley could anyone help me with parsing JSON Array.
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray jsonArray = response.getJSONArray("value");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject Image = (JSONObject) jsonArray.get(i);
urls = Image.getString("thumbnailUrl");
Log.d(TAG, "onResponse: "+urls);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try this
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray values = response.getJSONArray("value")
for (int i = 0; i < values.length(); i++) {
String url = values.getJSONObject(i).getString("thumbnailUrl");
//do something with the url
Log.d(TAG, url);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Well I found out the answer final which worked for me. I should have used JSONObject instead of JSONArray!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newRequestSearchImages(Constants.BING_ENDPOINT_SEARCH + Constants.QUERY + "puppies" + Constants.API_KEY);
}
private void newRequestSearchImages(String url){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray jsonArray = response.getJSONArray("value");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
jsonResponse = object.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
HolaApp.getInstance().addToRequestQueue(jsonObjectRequest);
}

JSONObject cannot be converted to JSONArray when requesting json

I've sent parameter to my server but in return it sent error message,
JSONObject cannot be converted to JSONArray
this is my code:
// Creating volley request obj
JsonObjectRequest taxiReq = new JsonObjectRequest (url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray taxiJsonArray = response.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray.length(); i++) {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(taxiJsonArray.getString("taxiname"));
taxi.setThumbnailUrl(taxiJsonArray.getString("image"));
taxi.setdeparture(taxiJsonArray.getString("departure"));
taxi.setarrive(taxiJsonArray.getString("arrive"));
taxi.setseat(taxiJsonArray.getInt("seat"));
taxi.setcost(taxiJsonArray.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
})
and this is my json:
{
"error": false,
"taxi_list": [
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
{
"image": "http://localhost/androidapp/taxiprofile/default.jpg",
"taxiname": "Taxi 2",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 2,
"cost": 15
},
{
"image": "http://localhost/androidapp/taxiprofile/2.jpg",
"taxiname": "Taxi Untung Selalu",
"from": "PTK",
"to": "SGU",
"departure": "09:00:00",
"arrive": "14:00:00",
"seat": 3,
"cost": 13
}
]
}
I've tried to change JSONObject to JSONArray but it still come with errors...
maybe because I tried to get object but there isn't one...
EDIT: new error, after I changed the code
error: incompatible types: String cannot be converted to int
in line:
taxi.setTaxiname(obj.getString("taxiname"));
any help?
you have to change your Volley request to JsonObjectRequest. So your code will be:
// Creating volley request obj
JsonObjectRequest taxiReq = new JsonObjectRequest (url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray taxiJsonArray = response.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray .length(); i++) {
try {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
})
Your "JSONArray response" is not a JsonArray It is a JsonObject try this once
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray responceArray = response.getJSONArray();
// Parsing json
for (int i = 0; i < responceArray.length(); i++) {
------------- Your code------------
}
}
You're expecting for a JSONArray, but your top level element is actually an object:
{ <--- This is a JSON Object
"error": false,
"taxi_list": [
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
You need to change this:
JsonArrayRequest taxiReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>()
To request a JsonObject instead.
Make StringRequest instead of JSONObjectRequest and use this method it will work fine.
Problems in your code:
you were taking values directly from array and not from jsonobject.
you were not checking for the response came from the server is correctly formatted in JSON or not. StringRequest will help you on that matter.
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.getString("error").equals("false")) {
JSONArray taxiJsonArray = jsonObject.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray.length(); i++) {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});

android parse jsonObject with volley

I first time try to parse json with volley. i found some examples and i learned how to use it.
but I have one problem....
i have like this json
{
"Items ":
[
{
"Branch" :"mybranch",
"City" : "London"
},
{
"Branch" :"mybranch1",
"City" : "Paris"
},
{
"Branch" :"mybranch2",
"City" : "NY"
}
]
}
and this is a my parser code
private void makeGetDictionaries13Request() {
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlgetbranchlist, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("TAG", response.toString());
try {
JSONArray mainjsonArray=response.getJSONArray("");
for (int i = 0; i < mainjsonArray.length(); i++) {
JSONObject j_object=mainjsonArray.getJSONObject(i);
System.out.println();
Log.e("City", j_object.getString("City"));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
I can show jsonobject result in log but i have volley error
no value for
for my option i have something wrong in parse son..what am i doing wrong?
There is a minor mistake in getting JSONArray from the JSONObject response. You actually forgot to mention the array name which is items.
Mistake:
JSONArray mainjsonArray=response.getJSONArray("");
Correct:
JSONArray mainjsonArray=response.getJSONArray("Items");
Use Items instead of "" for getting Items JSONArray from response JSONObject:
JSONArray mainjsonArray=response.getJSONArray("Items");

Volley throws error response when parsing JSON in Android

My volley throw error response when trying to parse JSON data inside listview. Is is because of my JSON data in object node, not array node.
JSON data
{
"users": [{
"userId": 1,
"name": "Dya Vega",
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "1 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 1 hour ago"
}, {
"userId": 2,
"name": "Esa Ezzatinor",
"profilePhoto": "https://graph.facebook.com/1269334432/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "2 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 2 hour ago"
}]
}
Code
// Creating volley request obj
JsonArrayRequest userReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Note:
=> if string contains { first character then string contain JSONObject as root container
=> if string contains [ first character then string contain JSONArray as root container
Posted json string contain JSONObject as root instead of JSONArray. use JsonObjectRequest instead of JsonArrayRequest for making request to server using Volley
You have users objects in an array inside an object. So you would want to start with a new JsonObjectRequest.
Edited: With the below code, you retrieve JSONObject type response, inside you have a JSONArray type users, after that you can loop through the JSONArray and retrieve each JSONObject from it.
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = response.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MainActivity onErrorResponse
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});

Categories

Resources