I'm getting a json response through volley, the response is as following :
{
"status":"success",
"message":"Request Successfull",
"messagetitle":"Success",
"show":"false",
"goback":"false",
"companies":[
{
"id":"14",
"category":{
"id":"1",
"name":"test"
},
"subcategory":{
"id":"1",
"name":"test",
"image":"https:\/\/page.com\/page\/uploads\/pagepics\/test\/testpics\/test.jpg"
},
"name2":"Company",
"location":null,
"logo":"https:\/\/page.com\/test\/testp\/testpics\/logo.png",
"picture":"https:\/\/page.com\/test\/",
"facebook":"https:\/\/www.facebook.com\/test",
"instagram":"",
"twitter":"",
"telephone1":"+9611990454",
"telephone2":"+961000000",
"address":"Lebanon",
"longitude":"0",
"latitude":"0",
"website":"www.website.com",
"email":"",
"desc":"asdasdas das das das dasda das das das dsadasdsadasdsad asd asd asd asd sad sa as das dsa asd das a a",
"user":{
"id":"21",
"name":"X Y"
},
"status":"1"
},
{
"id":"4",
"category":{
"id":"1",
"name":"test"
},
"subcategory":{
"id":"1",
"name":"test",
"image":"https:\/\/page.com\/test\/testp\/testpics\/test\/testphoto\/test.jpg"
},
"name2":"Your Company",
"location":null,
"logo":"",
"picture":"https:\/\/page.com\/test\/",
"facebook":"",
"instagram":"",
"twitter":"",
"telephone1":"",
"telephone2":"",
"address":"",
"longitude":"0",
"latitude":"0",
"website":"",
"email":"",
"desc":"",
"user":{
"id":"1",
"name":"X Y"
},
"status":"1"
}
]
}
I'm trying to get all "image" and "name2" objects from the response. Here is my java code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
link, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d("Request", response.toString());
try {
jarray1 = response.getJSONArray("subcategory");
for(int i=0;i<jarray1.length();i++)
{
JSONObject object = (JSONObject) jarray1.get(i);
String url = object.getString("image");
String name= object.getString("name2");
Toast.makeText(getBaseContext(),url+"\n"+name,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Well it's giving me wrong info, any help please ?
You can't directly access inner objects in JSON, according to your json format you have to first get JSON Array of companies
JSONArray companiesArray = response.getJSONArray("companies");
Then get elements of the array
for(int i=0;i<companiesArray .length();i++){
JSONObject object = (JSONObject) companiesArray.get(i);
// Now get subcategory information as JSONObject
JSONObject subcategoryObject =object .getJSONObject("subcategory");
// Now you can get image and name from subcategoryObject
String url = subcategoryObject.getString("image");
String name= subcategoryObject.getString("name2");
}
JSONArray jAry=response.getJSONArray("companies");
for(int k=0;k<jAry.size();k++)
{
String url = jAry.getJSONObject(k).getString("image");
String name= jAry.getJSONObject(k).getString("name2");
}
you have to use like above code to get the output from the json. I have given it for example
I figured it out :
try {
// response.getString("status");
jarray = response.getJSONArray("companies");
company_name=new String[jarray.length()];
for(int i=0;i<jarray .length();i++){
JSONObject object = (JSONObject) jarray.get(i);
// Now get subcategory information as JSONObject
// JSONObject subcategoryObject =object .getJSONObject("subcategory");
// Now you can get image and name from subcategoryObject
company_name[i]= object.getString("name2");
}
public void SendPost() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your_php_url");
try {
httppost.setEntity(new UrlEncodedFormEntity(postdata)); // Here postdata is BasicNameValuePair array with data to send
HttpResponse httpResponse = httpclient.execute(httppost);
String result = EntityUtils.toString(httpResponse.getEntity());
GetResponce(result);
} catch (UnsupportedEncodingException ex) {
} catch (IOException ex) {
} catch (JSONException ex) {
}
}
public void GetResponce(String responce) throws JSONException {
JSONObject myObject = new JSONObject(responce);
JSONArray companies = myObject.getJSONArray("companies");
String[] urls = new String[companies.length()];
String[] names = new String[companies.length()]; //Here i'm initializing the arrays
for (int i = 0; i < companies.length(); i++) {
JSONObject object = companies.getJSONObject(i);
JSONObject secondObject = object.getJSONObject("subcategory");
urls[i] = secondObject.getString("image");
names[i] = object.getString("name2");
}
}
Related
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.
public void onResponse( String response ){
JSONArray jsonArray ;
try{
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);
}
catch(JSONException e){
e.printStackTrace();
}
}
and my json file is
[
{
"0":"1",
"1":"Adarsh",
"id":"1",
"name":"Adarsh"
},
{
"0":"2",
"1":"Asif",
"id":"2",
"name":"Asif"
},
{
"0":"3",
"1":"Baba",
"id":"3",
"name":"Baba"
},
{
"0":"4",
"1":"Beeta",
"id":"4",
"name":"Beeta"
}
]
In my application it doesn't retrieve the value for "name" instead showing error toast.
jsonArray has not been initialised
jsonArray = new JSONArray("yourjson");
String name = jsonArray.getJSONObject(1).getString("name");
First change your string response to json response like this:
JsonArray jarray=new JsonArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);
Here you are trying to fetch data from string as per your comment so need to convert in to json first like this
public void onResponse( String response ){
try{
JSONArray jsonArray= new JSONArray(response);
Log.d("JsonArray", jsonArray.toString());
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);
}
catch (Throwable t) {
Log.e("ERROR", "Wrong Json format");
}
catch(JSONException e){
e.printStackTrace();
}
}
I have made a call to the Instagram Endpoint for images that contain the tag #selfie. The issue I am having is in dealing with the response. I get a massive JSON Response, and all I really need is the "thumbnail" image "url".
How can I go about structuring an Object from the Data that is in the JSONObject?
public static class FetchTaggedImages extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
String mAccessToken = params[0];
String url = (API_URL + "?access_token=" + mAccessToken);
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
String instagramJSONResponse = null;
JSONArray responseArray = null;
HttpResponse postResponse;
try {
postResponse = httpclient.execute(httpGet);
instagramJSONResponse = EntityUtils.toString(postResponse
.getEntity());
JSONObject jsonObject = new JSONObject(instagramJSONResponse);
String thumbnail = jsonObject.getString("url");
responseArray = new JSONArray(instagramJSONResponse);
Log.e("RESPONSE", instagramJSONResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
return responseArray;
}
#Override
protected void onPostExecute(JSONArray response) {
// TODO Auto-generated method stub
super.onPostExecute(response);
Log.e("ONPOSTEXECUTE", "ONPOSTEXECUTE");
JSONObject jsonObject;
}
}
HERE IS A SAMPLE OF THE JSON STRING
{
"data":[
{
"tags":[
"summer",
"love",
"tagstagram",
"colorful",
"instalike",
"selfie",
"swag",
"instago",
"igers",
"follow4follow",
"follow",
"instadaily",
"friends",
"style",
"webstagram",
"look",
"instafollow",
"iphoneonly",
"instagood",
"amazing",
"instacool",
"bestoftheday",
"fun",
"followme",
"like4like",
"picoftheday",
"photooftheday"
],
"location":null,
"link":"http:\/\/instagram.com\/p\/wFlirqPxAW\/",
"user_has_liked":false,
"caption":{
"id":"866263615190011927",
"created_time":"1417486691",
"text":"First contest of the season 🏄",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
},
"type":"image",
"id":"866263614401482774_507279035",
"likes":{
"data":[
{
"id":"956576929",
"profile_picture":"https:\/\/igcdn-photos-e-a.akamaihd.net\/hphotos-ak-xfa1\/10802992_1561400387426348_1634151041_a.jpg",
"username":"don_assi2014",
"full_name":"-Ali Assi-"
},
{
"id":"520771011",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfa1\/1889350_1565133803717465_1353157813_a.jpg",
"username":"michelle.y6",
"full_name":"Michelle Y"
},
{
"id":"873300277",
"profile_picture":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xfa1\/10817804_1543101285933854_123980756_a.jpg",
"username":"ayah_shahbanderr",
"full_name":"Ayah"
},
{
"id":"199966711",
"profile_picture":"https:\/\/igcdn-photos-a-a.akamaihd.net\/hphotos-ak-xfa1\/10617174_587781691338392_1164910966_a.jpg",
"username":"elijah_reissman_",
"full_name":"Elijah Reissman"
}
],
"count":13
},
"images":{
"low_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_a.jpg",
"height":306,
"width":306
},
"standard_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_n.jpg",
"height":640,
"width":640
},
"thumbnail":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_s.jpg",
"height":150,
"width":150
}
},
"users_in_photo":[
],
"created_time":"1417486691",
"user":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"bio":"",
"website":"",
"full_name":"Juan Basave"
},
"filter":"Mayfair",
"comments":{
"data":[
{
"id":"866282245801841449",
"created_time":"1417488912",
"text":"#TagStaGram #love #friends #tagstagram #photooftheday #selfie #amazing #followme #follow4follow #like4like #look #instalike #igers #picoftheday #instadaily #instafollow #fun #iphoneonly #instagood #bestoftheday #instacool #instago #summer #follow #webstagram #colorful #style #swag",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
}
],
"count":1
},
"attribution":null
},
"thumbnail" is in "images" object, and "images" object is in a first object of the "data" array.
So you need to obtain the "data" JSONArray first, access for each array item, find "images" object from the item, and finally you can access "thumbnail" object.
Your code seems to access to "url" in the top level object that does not have "url" property.
If you'd like to access via JSONObject framework, you should implement the code like this:
public String getUrl(JSONObject response) throws JSONException {
JSONArray data = response.getJSONArray("data");
JSONObject object = data.getJSONObject(0);
JSONObject images = object.getJSONObject("images");
JSONObject thumbnail = images.getJSONObject("thumbnail");
return thumbnail.getString("url");
}
If you need a collection of the url, you need to iterate accessing all data objects like this:
JSONArray data = response.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(0);
// ...
}
This is a basic function for dealing with JSON string that Android Framework provides.
If you feel that it is a long way to go, consider using GSON or Jackson JSON Processor.
I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}