I'm using Android Networking and by using get, I get the data and this is the API that I'm calling.
String url = baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}"
and getting the response like this
[{"permit_to_use":null,"min":null,"company_id":"4ed8954c-703e-41b5-94ba-eeb29546e3e3","model":"q1","bus_id":"b6d52ce3-3672-4230-9f9e-a6a465c1c8ea","sam_card":"04042DE2E52080","sim_number":null,"device_serial":"WP18121Q00000410","created_on":"2018-05-24T13:28:28.251004+00:00","remarks":null,"location_id":"ec176824-4cb7-4376-a436-429b529f8b45","id":"36bc07be-7d93-4209-ba15-9c9da7a58c3c","device_name":"wizarpos-ken","is_activated":"1","qrcode":null,"is_assigned":"1","sd_serial":"1510124e436172641068a36718010b00","updated_on":"2018-06-07T09:18:29.365416+00:00","software_serial":null,"subcompany_id":{"name":"MAN LINER"},"sim_serial":"89630317324030972665"}]
notice that subcompany_id has a another JSONArray. how can i get the name inside of it?
I'm using Android Fast Networking and this is the entire process
AndroidNetworking.get(baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}")
.setPriority(Priority.HIGH)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", String.valueOf(response));
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String raw_id = jresponse.get("id").toString();
String id_string = raw_id;
id_string = id_string.replace("\"", "");
String id_final = String.valueOf(id_string);
String raw_company_id = jresponse.get("company_id").toString();
String company_id_string = raw_company_id;
company_id_string = company_id_string.replace("\"", "");
String company_id_final = String.valueOf(company_id_string);
String raw_subcompany_id = jresponse.get("subcompany_id").toString();
String subcompany_id_string = raw_subcompany_id;
subcompany_id_string = subcompany_id_string.replace("\"", "");
String subcompany_id_final = String.valueOf(subcompany_id_string);
String raw_location_id = jresponse.get("location_id").toString();
String location_id_string = raw_location_id;
location_id_string = location_id_string.replace("\"", "");
String location_id_final = String.valueOf(location_id_string);
String raw_bus_id = jresponse.get("bus_id").toString();
String bus_id_string = raw_bus_id;
bus_id_string = bus_id_string.replace("\"", "");
String bus_id_final = String.valueOf(bus_id_string);
CompanyID = company_id_final;
BusID = bus_id_final;
subCompID = subcompany_id_final;
dbmanager.insertToDeviceInformation(id_final,
company_id_final,
subcompany_id_final,
location_id_final,
bus_id_final);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Make a new JSONObject JSONObject response = jresponse.get("subcompany_id"), then initialize your String name = response.get("name")
"subcompany_id":{"name":"MAN LINER"}
This is JSONObject not JSONArray, JSONArray start with [{ }]
So you can get "name" with JSONObject like this.
JSONObject jsonObjectSubCompanyId = jresponse.getJSONObject("subcompany_id");
String name = jsonObjectSubCompanyId.getString("name");
Related
Hi I am trying to print a JSON response into a readable form that I can then set to a Textview. This is the code where I am trying to print the JSON response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("json", response);
//Creating JsonObject from response String
JSONObject jsonObject = new JSONObject(response);
//extracting json array from response string
JSONArray jsonArray = jsonObject.getJSONArray("data");
JSONObject jsonRow = jsonArray.getJSONObject(0);
//get value from jsonRow
leaderboardView.setText(jsonArray.toString());
it does print the JSON but in a JSON format. this is the JSON format I am receiving.
{"data":[{"username":"DolanF","score":"4220","rank":"1"},{"username":"reyay","score":"3760","rank":"2"},{"username":"MeghanG","score":"2570","rank":"3"},{"username":"PrimGosling","score":"1360","rank":"4"},{"username":"JakubRozanski","score":"1190","rank":"5"},{"username":"rodyquigley","score":"1120","rank":"6"},{"username":"Kaz835","score":"800","rank":"7"},{"username":"bailey","score":"570","rank":"8"},{"username":"Ellis","score":"430","rank":"9"},{"username":"Joel","score":"390","rank":"10"}]}
my goal is to get the username, rank and score printing in a readable format each row underneath each other.
Change:
jsonArray.toString()
in to:
jsonArray.toString(4)
Parameter (for example 4 - like above) is the number of spaces to indent for each level of nesting.
You can expect this output:
Here you have example in Kotlin how you can get all data as variable:
fun readJson() {
val response =
"{\"data\":[{\"username\":\"DolanF\",\"score\":\"4220\",\"rank\":\"1\"},{\"username\":\"reyay\",\"score\":\"3760\",\"rank\":\"2\"},{\"username\":\"MeghanG\",\"score\":\"2570\",\"rank\":\"3\"},{\"username\":\"PrimGosling\",\"score\":\"1360\",\"rank\":\"4\"},{\"username\":\"JakubRozanski\",\"score\":\"1190\",\"rank\":\"5\"},{\"username\":\"rodyquigley\",\"score\":\"1120\",\"rank\":\"6\"},{\"username\":\"Kaz835\",\"score\":\"800\",\"rank\":\"7\"},{\"username\":\"bailey\",\"score\":\"570\",\"rank\":\"8\"},{\"username\":\"Ellis\",\"score\":\"430\",\"rank\":\"9\"},{\"username\":\"Joel\",\"score\":\"390\",\"rank\":\"10\"}]} \n" +
"\n"
val jsonObject = JSONObject(response)
val jsonArray = jsonObject.getJSONArray("data")
var output = ""
for (position in 0 until jsonArray.length()) {
val row = jsonArray.getJSONObject(position)
val name = row.getString("username")
val score = row.getString("score")
val rank = row.getInt("rank")
output += String.format("%s - %s (rank: %s)\n", name, score, rank)
}
text_view.text = output
}
Or in Java:
void readJson() {
String response =
"{\"data\":[{\"username\":\"DolanF\",\"score\":\"4220\",\"rank\":\"1\"},{\"username\":\"reyay\",\"score\":\"3760\",\"rank\":\"2\"},{\"username\":\"MeghanG\",\"score\":\"2570\",\"rank\":\"3\"},{\"username\":\"PrimGosling\",\"score\":\"1360\",\"rank\":\"4\"},{\"username\":\"JakubRozanski\",\"score\":\"1190\",\"rank\":\"5\"},{\"username\":\"rodyquigley\",\"score\":\"1120\",\"rank\":\"6\"},{\"username\":\"Kaz835\",\"score\":\"800\",\"rank\":\"7\"},{\"username\":\"bailey\",\"score\":\"570\",\"rank\":\"8\"},{\"username\":\"Ellis\",\"score\":\"430\",\"rank\":\"9\"},{\"username\":\"Joel\",\"score\":\"390\",\"rank\":\"10\"}]} \n" +
"\n";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
StringBuilder output = new StringBuilder();
for (int position = 0; position < jsonArray.length(); position++) {
JSONObject row = jsonArray.getJSONObject(position);
String name = row.getString("username");
String score = row.getString("score");
int rank = row.getInt("rank");
output.append(String.format("%s - %s (rank: %s)\n", name, score, rank));
}
text_views.setText(output.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
And output is:
String url = Config.DATA_URL+TempItem.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
This is the constructor where I parse in my response.
I am a total beginner in android studio and I have no idea how to solve this error. I have read other forums which I tried implementing to no avail. My JSON result is
"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100",
"RequiredTotal":"200",
"MaxTotal":"500"
}
]
}
private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
String results= jsonObject.getString(Config.JSON_ARRAY);
JSONArray result = new JSONArray(results);
JSONObject stallsData = result.getJSONObject(0);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
This is to change my JSONObject to JSONArray.
Edit:
This is my php file
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('conn.php');
$sql = "SELECT * FROM business WHERE BusinessID='".$id."'";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"BusinessName"=>$res["BusinessName"],
"AmountTotal"=>$res["AmountTotal"],
"RequiredTotal"=>$res["RequiredTotal"],
"MaxTotal"=>$res["MaxTotal"]
)
$str = json_encode(array("result"=>$result)); $str=str_replace('','',$str); $str=str_replace('','',$str); echo $srt;
echo json_encode(array("result"=>$result));
);
mysqli_close($conn);
}
this is my config file.
public class Config {
public static final String DATA_URL = "http://192.168.1.2/retrieveone.php?id=";
public static final String KEY_NAME = "BusinessName";
public static final String KEY_AmountTotal = "AmountTotal";
public static final String KEY_RT = "RequiredTotal";
public static final String KEY_MT = "MaxTotal";
public static final String JSON_ARRAY = "result";
}
You are parsing data wrongly. Try below code -
JSONArray result = jsonObject.getJSONArray("result");
JSONObject stallsData = result.getJSONObject(0);
Here i am doing some changes in your code .
{"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100",
"RequiredTotal":"200",
"MaxTotal":"500"
} ] }
this will be your actual response.
now i am going to parse it.
` private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result"); // this line is new
for(int i=0;i<result.length;i++){
JSONObject stallsData = result.getJSONObject(i);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
}Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
you can write
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("result");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String BusinessName= jo.getString("BusinessName");
String AmountTotal= jo.getString("AmountTotal");
String RequiredTotal= jo.getString("RequiredTotal");
String MaxTotal= jo.getString("MaxTotal");
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi i am completely new to android.please suggest me how to parse the below jsonresposne and get the values.any help please suggest me.i don't know how to parse because it contains both square bracket and curly bracket.
`[
{
"bus_schedule":[
{
"bus_route":[
{
"serviceDate":"2016-12-31",
"amenities":" VB King Size Semi Sleeper (2 plus 1) selected WIFI,Water,Bottle,Blankets,Snacks,Movie,Food,Emergency exit, Fire Extinguisher,Bus Hostess,CCTV,Emergency Contact Number",
"startCityName":"Coimbatore",
"departureTime":"21:00:00",
"fare":"499",
"endCityName":"Kanyakumari",
"arrivalTime":"06:00:00",
"operatorName":"RUN TO WIN",
"bus_id":"17",
"journeyHours":"9",
"available_seat":25,
"total_seats":34,
"seat_type":"semi sleeper"
}
],"boardingPoint":[
{
"boardingPointName":"Thudiyalur",
"boardingPointContact":"8883088820",
"boardingPointTime":"21:25:00",
"boardingPointId":"316",
"BusId":"17"
},`
my code is
`protected Void doInBackground(Void... params) {
HttpGet request = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
response= mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
return null;
} catch (IOException exception) {
exception.printStackTrace();
return null;
}
Log.i("routes",""+response);
jsonstr=response;
if(jsonstr!= null){
try{
/*JSONArray jsonary=new JSONArray(jsonstr);
JSONArray bus_scheduleee=jsonary.getJSONArray("bus_schedule");*/
JSONObject jsonObj = new JSONObject(jsonstr);
JSONArray bus_schedule = jsonObj.getJSONArray("bus_schedule");
JSONArray bus_route = jsonObj.getJSONArray("bus_route");
for (int i = 0; i < bus_route.length(); i++) {
JSONObject c = bus_route.getJSONObject(i);
String journeydatefromjson=c.getString("serviceDate");
String busname=c.getString("amenities");
String fromplace_json=c.getString("startCityName");
String departtimejson=c.getString("departureTime");
String farefromjson=c.getString("fare");
String endCityNamejson=c.getString("endCityName");
String arrivalTimejson=c.getString("arrivalTime");
String operatorNamejson=c.getString("operatorName");
String bus_idjson=c.getString("bus_id");
String journeyHoursjson=c.getString("journeyHours");
String available_seatjson=c.getString("available_seat");
String total_seatsjson=c.getString("total_seats");
String seat_typejson=c.getString("journeyHours");
Log.d("busdetails",""+journeydatefromjson+busname);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}`
Try use Gson lib for parse it.
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
You can generation pojo for parse json. (For example on this site http://www.jsonschema2pojo.org)
For parse use this.
T t = new Gson().fromJson(serverResponse.getResponse(), type);
Where 'T' is your response data, and 'type' it pojo from site.
If your type is entity use Type type = Entity.class;
If your type is list of entities use
Type type = new TypeToken<List<WadadayFull>>() {
}.getType())
try this code:
try {
JSONArray array1 = new JSONArray(str);
for (int i=0;i<array1.length();i++){
JSONObject obj1 = array1.getJSONObject(i) ;
JSONArray array2 = obj1.getJSONArray("bus_schedule");
for (int j=0;j<array2.length();j++){
JSONObject obj2 = array2.getJSONObject(j);
JSONArray array3 = obj2.getJSONArray("bus_route");
ArrayList<Example1> list = new ArrayList<>();
for (int k=0;k<array3.length();k++) {
JSONObject obj3 = array3.getJSONObject(k);
String s1 = obj3.getString("serviceDate");
String s2 = obj3.getString("amenities");
String s3 = obj3.getString("startCityName");
String s4 = obj3.getString("departureTime");
String s5 = obj3.getString("fare");
String s6 = obj3.getString("endCityName");
String s7 = obj3.getString("arrivalTime");
String s8 = obj3.getString("operatorName");
String s9 = obj3.getString("bus_id");
String s10 = obj3.getString("journeyHours");
String s11 = obj3.getString("available_seat");
String s12 = obj3.getString("total_seats");
String s13 = obj3.getString("seat_type");
Example1 ex1 = new Example1();
ex1.setServiceDate(s1);
ex1.setAmenities(s2);
ex1.setStartCityName(s3);
list.add(ex1);
Log.e("response", list.toString());
}
JSONArray array4 = obj2.getJSONArray("boardingPoint");
ArrayList<Example2> list2 = new ArrayList<>();
for (int l = 0; l < array4.length(); l++) {
JSONObject obj4 = array4.getJSONObject(l);
String s14 = obj4.getString("boardingPointName");
String s15 = obj4.getString("boardingPointContact");
String s16 = obj4.getString("boardingPointTime");
String s17 = obj4.getString("boardingPointId");
String s18 = obj4.getString("BusId");
Example2 ex2 = new Example2();
ex2.setBoardingPointName(s14);
ex2.setBoardingPointContact(s15);
list2.add(ex2);
Log.e("response", list2.toString());
}
}
}
Log.e("response",array1.toString());
} catch (JSONException e) {
e.printStackTrace();
}
In my application I am receiving a JSON object as
{"secQueList":{"1":"Which is your favorite book?","2":"Who was your childhood hero?","3":"What is your pet's name?","4":"What make was your first car or bike?","5":"What is your favorite color?","6":"Which is your favorite sports team?","7":"What was the name of your school?","8":"What is your mother's maiden name?","9":"Which is your birthplace?","10":"Which is your favourite sport?","11":"Which is your favourite place of visit?"},"que1":null,"ans1":null,"message":null,"fieldErrors":null}
I am not able to figure out how exactly should i parse this object.
I tried using the below code but as this not a JSONArray it throws an exception.
String getParam(String code, String element){
try {
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONArray jarray = product.getJSONArray("item");
String param = jarray.getJSONObject(0).getString("name");
return param;
} catch (JSONException e) {
e.printStackTrace();
return "error";
}
}
I recommend you use sites for json formater which show to you the types of json elements as http://json.parser.online.fr/
and
you can use Gson library for parsing json by using pojo class
public class secQueList {
public String que1;
public int ans1;
public String message;
public String nextPage;
public QuestionList secQueList;
}
public class QuestionList {
#SerializedName("1")
public String ques1;
#SerializedName("2")
public int ques2;
#SerializedName("3")
public String ques3;
#SerializedName("4")
public String ques4;
#SerializedName("5")
public String ques5;
#SerializedName("6")
public String ques6;
#SerializedName("7")
public int ques7;
#SerializedName("8")
public String ques8;
#SerializedName("9")
public String ques9;
#SerializedName("10")
public String ques10;
#SerializedName("11")
public String ques11;
}
or you can use parse using built in JSON Object
String jsonBody = the string you want to parse
JSONObject quesJsonBody = new JSONObject(jsonBody);
JSONOBject quesJson = quesJsonBody.getJSONObject("secQueList");
String quesJson1 = quesJson.getString("1");
String quesJson2 = quesJson.getString("2");
String quesJson3 = quesJson.getString("3");
String quesJson4 = quesJson.getString("4");
String quesJson5 = quesJson.getString("5");
String quesJson6 = quesJson.getString("6");
String quesJson7 = quesJson.getString("7");
String quesJson8 = quesJson.getString("8");
String quesJson9 = quesJson.getString("9");
String quesJson10 = quesJson.getString("10");
String quesJson11 = quesJson.getString("11");
String que1 = quesJsonBody.getString("que1");
String ans1 = quesJsonBody.getString("ans1");
String message = quesJsonBody.getString("message");
String fieldErrors = quesJsonBody.getString("fieldErrors");
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONOBject secQueListJson = product.getJSONObject("secQueList");
// Get all json keys "1", "2", "3" etc in secQueList, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = secQueListJson .entrySet ();
Iterator iterator = entrySet.iterator ();
for (int j = 0; j < entrySet.size (); j++) {
String key = null; //key = "1", "2", "3" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "1", "2", "3" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = secQueListJson.getString(key);
//for key = "1", value = "Which is your favorite book?"
//for key = "2", value = "Who was your childhood hero?"
}
}
Try something like this:
JSONObject jsonObject = new JSONObject(code);
JSONObject jsonObject1 = jsonObject.getJSONObject("secQueList");
for (int i=0;i<jsonObject1.length();i++){
String msg = jsonObject1.getString(String.valueOf(i));
}
You can try to use Gson to parse it. I used code below in my App in similiar case:
ArrayList<String> myArrayList;
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<String>>(){}.getType();
myArrayList= gson.fromJson(code, type);
You have to add gson to your build.grandle to have it working
compile 'com.google.code.gson:gson:2.2.+'
Extract Data from JSON String
public void ReadSMS_JSON(String JSON_String) {
String smsID = "";
String phone = "";
String message = "";
JSONObject jsonResponse = new JSONObject(JSON_String);
JSONArray jsonMainNode = jsonResponse.optJSONArray("tblsms");
if(jsonMainNode.length()>0){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
smsID = jsonChildNode.optString("sms_id");
phone = jsonChildNode.optString("sms_number");
message = jsonChildNode.optString("sms_message");
}
}
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);
}
}