Unable to fetch data from Json volley - android

I'm unable to fetch from this type of JSON, I'm confused in how to get data from inside of JsonObject, I got the value of "dealer_name", "phone_no" and "address" but I'm not getting the value of other.
This is my Solution.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
urlLink, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("suraj", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
String name = response.getString("dealer_name");
String phone_no = response.getString("phone_no");
String add = response.getString("address");
JSONObject phone = (JSONObject) response.get(String.valueOf(i));
String acc_name = phone.getString("auto_dealer_id");
String acc_price = phone.getString("accessory_price");
jsonResponse = "";
jsonResponse += "dealer_name: " + name + "\n\n";
jsonResponse += "dealer_phone: " + phone_no + "\n\n";
jsonResponse += "dealer_add: " + add + "\n\n";
jsonResponse += "acc_name: " + acc_name + "\n\n";
jsonResponse += "acc_price: " + acc_price + "\n\n";
}
txt.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(Activity3.this).add(jsonObjReq);
}
This is my JSON data:-
{
"auto_dealer_id": "1",
"dealer_name": "RAJ MOTORS",
"phone_no": "9004296356",
"address": "THANE WEST 40002",
"0": {
"auto_dealer_accessory_id": "1",
"auto_dealer_id": "1",
"accessory_name": "CAR OILING",
"accessory_price": "40"
},
"1": {
"auto_dealer_accessory_id": "2",
"auto_dealer_id": "1",
"accessory_name": "CAR WASHING",
"accessory_price": "40"
},
"2": {
"auto_dealer_gallery_id": "1",
"auto_dealer_id": "1",
"image": "1.jog",
"status": "1",
"sort": "1",
"added_date": "0000-00-00 00:00:00"
}
}

try this code:
try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString);
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("key Items", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
but it is better approach to convert you JsonObject "1","2"... to JsonArray

Since you want to get json object inside json object,
here you can get
JSONObject number = response.getJSONObject("1");
number.getString("auto_dealer_accessory_id")
and so on.
But there are some better approaches as well. Use Gson and also improve your data structure coming from server. using an array is better option and don't forget to check if the object or string exists before you try to get a value. you can use
jsonObject.has("key")

Try this:
ArrayList acc_name = new ArrayList();
...
...
try
{
JSONObject obj=new JSONObject(responseString);
String name = obj.getString("dealer_name");
String phone_no = obj.getString("phone_no");
String add = obj.getString("address");
Iterator<String> keys = obj.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONObject innerJObject = obj.getJSONObject(key);
Iterator<String> inKeys= innerJObject .keys();
while( inKeys.hasNext() )
{
String inKeys= keys.next();
acc_name.Add(innerJObject .getString(inKeys);
..
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

How to parse nested json array in android using volley library

I have nested json array in below format.I am using volley liabrary for JSON Parsing.
{
"City": [{
"name": "Mumbai",
"Mumbai": [{
"area": "andheri",
"diler": [{
"DName": "yuvraj"
}]
}, {
"area": "jogeshwari"
}, {
"area": "goregaon"
}]
},
{
"name": "Nashik",
"Nashik": [{
"area": "clg rd",
"diler": [{
"DName": "yuvraj"
}]
}, {
"area": "GP RD",
"diler": [{
"DName": "Roshan"
}]
}, {
"area": "CBS",
"diler": [{
"DName": "Deepak"
}]
}]
}, {
"name": "Bengaluru"
}
]}
Below is the code which i have write in android.
jsonURL = "http://192.168.1.11/cycle_webservices/testing.json";
buttonReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
jsonURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
String name = jsonObject.getString("name");
String area = jsonObject.getString("area");
String diler = jsonObject.getString("diler");
textView.append("\nCity: " + name + "\nArea: " + area + "\nDealer: " + diler + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
});
But i am getting Errors while parsing it in Android.
The error is- JSONObject can not be converted to JSONArray
Can anyone please provide sample code to parse this json Array.
Thanks in Advance
Here is your problem solution, use below code
try {
JSONObject jsonObject = new JSONObject("response");
JSONArray jsonArray = jsonObject.getJSONArray("City");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name");
if (object.length() != 0) {
Iterator<String> key = object.keys();
while (key.hasNext()) {
String cityname = key.next();
JSONArray ja = object.getJSONArray(cityname);
for (int j = 0; j < ja.length(); j++) {
JSONObject object1 = ja.getJSONObject(j);
String area = object1.getString("area");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
And try to make your JSON format same.
The point is the first json node is a JsonObject,
change your code this way and continue parsing:
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Use JSONObject for parsing data like:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("City");
for(int i = 0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray .getJSONObject(i);
String name = jsonObject.getString("name");
JSONArray city_array = jsonObject.getJSONArray(name);
for(int j=0; j<city_array.length(); j++)
{
JSONObject obj = city_array.getJSONObject(j);
String area = obj.getString("area");
JSONArray diler_array = obj.getJSONArray("diler");
JSONObject obj1 = diler_array.getJSONObject(0);
String DName = obj1.getString("DName");
}
}
Please check edited answer.
pass data array inside array in android using volley
public List<HashMap<String,String>> returnJsonforPhp(){
HashMap<String,String> map = new HashMap<String,String>();
List<HashMap<String,String>> forjson= new ArrayList<HashMap<String,String>>();
/*for(int i=0;i<dblist;i++) {
map.put("name",dblist.getName());
map.put("email",dblist.getEmail());
map.put("mobno",dblist.getMobno());
forjson.add(map);
}*/
map.put("name","ravi");
map.put("email","ravi#gmail.com");
map.put("mobno","9897939595");
forjson.add(map);
return forjson;
}
String OTP_Url = "https://www.yourdomain.com/rest/updateregistration/";
public String getJson() throws JsonProcessingException {
List> list = new ArrayList>();
List>> newlist = new ArrayList>>();
newlist.add(list);
HashMap<String,String> map = new HashMap<String, String>();
map.put("name","knnkl");
map.put("email","kjbjbk");
map.put("password","njnjknk");
list.add(map);
newlist.add(list);
String parsedJson = new ObjectMapper().writeValueAsString(newlist);//json conversion
return parsedJson;
}
compile (
[group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1']
)

How to get Multiple return value From JSON in Android

I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)

How to get complex JSON from URL?

My json is like this
{
"results": [{
"syllabus": "CBSE",
"grade": "5",
"subject": "Kannada",
"topic": "Grammar Level 1",
"id": 28
}]
}
Using Volley
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
Your Json have an object and then array.. try like this
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONOArray array = response.getJSONArray("results")
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < array.length(); i++) {
JSONObject person = (JSONObject) array
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
if (!result.equalsIgnoreCase("")) {
try {
JSONObject jsonObject = new JSONObject(result); //result is what you get responce
JSONArray jsonArray = jsonObject.optJSONArray("results");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String syllabus = jsonObjects.optString("syllabus");
Int grade = jsonObjects.optInt("grade");
String subject = jsonObjects.optString("subject");
String topic = jsonObjects.optString("topic");
Int id = jsonObjects.optInt("id");
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} catch (Exception e) {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}

Get errror JSONException: No Value For

i have a problem with json parsing code it shows error json no value for konteks lokasi which is use TAG_KONTEKS variable.
This is my code for get json response.
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//mendapatkan data dari database berupa alamat, konteks, latitude, longitude
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat", Integer.toString(latPengguna)));
params.add(new BasicNameValuePair("lng", Integer.toString(lngPengguna)));
params.add(new BasicNameValuePair("konteks", konteksCocok));
Log.d("lat dan lng kirim", "data: " + Integer.toString(latPengguna) + " " + Integer.toString(lngPengguna));
Log.d("konteks kirim", "data: " + konteksCocok);
JSONObject json = jParser.makeHttpRequest(url_webservice, "POST", params);
Log.d("data: ", json.toString());
//menampilkan data lokasi POI
try {
int sukses = json.getInt(TAG_SUCCESS);
if(sukses == 1) {
POI = json.getJSONArray(TAG_POIN);
for(int i = 0; i < POI.length(); i++) {
JSONObject c = POI.getJSONObject(i);
int latDB = c.getInt(TAG_LAT);
int lngDB = c.getInt(TAG_LNG);
String alamat = c.getString(TAG_ALAMAT);
String konteks = c.getString(TAG_KONTEKS);
Log.d("latDB", "data: " + latDB);
Log.d("lngDB", "data: " + lngDB);
Log.d("altDB", "data: " + alamat);
Log.d("ktsDB", "data: " + konteks);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ALAMAT, alamat);
map.put(TAG_KONTEKS, konteks);
POIList.add(map);
}
} else {
Log.d("JSON error", "JSON trouble");
}
} catch(JSONException ex) {
ex.printStackTrace();
}
return null;
}
This is my json response:
{
"success": 1,
"point": [
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Perkapalan",
"longitude": "-60",
"latitude": "117"
},
"hasil": 15.811388300842
},
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Kimia",
"longitude": "-80",
"latitude": "145"
},
"hasil": 33.376638536557
},
{
"point": {
"konteks_lokasi": "kuliah",
"nama_lokasi": "Teknik Arsitektur",
"longitude": "-22",
"latitude": "111"
},
"hasil": 53.009433122794
}
]
}
I would be very happy if you could help me...
Longitude and Latitude are strings, as they are surrounded by quotes. so you should get them with getString()
parse them like this
Your JSONArray contain another json Array so parse it like this
int sukses = json.getInt(TAG_SUCCESS);
if(sukses == 1) {
POI = json.getJSONArray(TAG_POIN);
for(int i = 0; i < POI .length(); i++) {
JSONObject c = POI .getJSONObject(i);
JSONObject d = c.getJSONObject(0);
String latDB = d.getString(TAG_LAT);
String lngDB = d.getString(TAG_LNG);
String alamat = d.getString(TAG_ALAMAT);
String konteks = d.getString(TAG_KONTEKS);
}

Categories

Resources