Given below is my JSON response from web-service.
{"message":"success","data":[{"push_status":"1"}]}
I want to get the value of push_status from {"push_status":"1"}.
This is my code:
public static VehicleDetails getPushNotificationstatus(String clientCode, String secretode) throws ClientProtocolException,
IOException, JSONException {
Log.d(WebServiceHelper.TAG, "getPushNotificationstatus==============>");
VehicleDetails vdetails = null;
String result;
ArrayList<VehicleDetails> SIArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
try {
Log.d(WebServiceHelper.TAG, "WebserviceHelperOnLogin>>>>>>>>>>>");
vdetails = new VehicleDetails();
METHOD_NAME = "getPushNotifyStatus";
Log.d(WebServiceHelper.TAG, "URL>>>>>>>>" + URL + METHOD_NAME);
HttpPost request = new HttpPost(URL + METHOD_NAME);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("clientCode", clientCode));
postParameters.add(new BasicNameValuePair("secretCode", secretode));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(entity);
HttpResponse response = getThreadSafeClient().execute(request);
entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
// Log.i("FB", "result ::: " + result);
Log.d(TAG, "ResultPushStatus>>>>" + result);
jObject = new JSONObject(result);
vdetails.status_login = jObject.getString("message");
// Log.i("FB", "contact.status_login ::: " + contact.status_login);
if (vdetails.status_login.contentEquals("success")) {
jObject = new JSONObject(jObject.getString("data"));
vdetails.pushStatus = jObject.getString("push_status");
Log.d(TAG, "Push Status==================>" + vdetails.pushStatus);
} else if (vdetails.status_login.contentEquals("failed")) {
String Reason = jObject.getString("data").toString();
Log.d(WebServiceHelper.TAG, "Fail Reason>>>>>" + Reason);
vdetails.failReason = Reason;
}
} catch (Exception e) {
e.printStackTrace();
}
return vdetails;
}
public static VehicleDetails[] getAllVehicles(String clientCode, String
secretCode) throws ClientProtocolException, IOException, JSONException {
VehicleDetails[] vd = null;
String result = null;
VehicleDetails vdetails = null;
ArrayList<VehicleDetails> vehicleArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
String loginUrl = "getAllVehicles";
try {
HttpPost request = new HttpPost(URL + loginUrl);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("clientCode", clientCode));
postParameters.add(new BasicNameValuePair("secretCode", secretCode));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
HttpResponse response = getThreadSafeClient().execute(request);
entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
Log.d(TAG, "result>>" + result);
JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
VehicleDetails.status_login = object.getString("message");
if (VehicleDetails.status_login.contentEquals("success")) {
JSONArray array = object.getJSONArray("data");
vehicleArrayList.clear();
for (int i = 0; i < array.length(); i++) {
Log.d(TAG, "LiveTracking>>>>>>>>>>>");
JSONObject jObj = array.getJSONObject(i);
String vehicleId = jObj.getString("vehicle_id").toString();
String vehicleNumber = jObj.getString("vehicle_number").toString();
vdetails = new VehicleDetails();
vdetails.vehicleId = vehicleId;
vdetails.vehicleNo = vehicleNumber;
vehicleArrayList.add(vdetails);
}
vd = new VehicleDetails[vehicleArrayList.size()];
for (int x = 0; x < vehicleArrayList.size(); ++x) {
vd[x] = (VehicleDetails) vehicleArrayList.get(x);
}
} else if (VehicleDetails.status_ login.contentEquals("failed")){
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jObj = array.getJSONObject(i);
vdetails.failReason = jObj.getString("data").toString();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return vd;
}
This is my log show.
05-02 14:34:40.597: W/System.err(10261): org.json.JSONException: Value [{"push_status":"1"}] of type org.json.JSONArray cannot be converted to JSONObject
05-02 14:34:40.617: W/System.err(10261): at org.json.JSON.typeMismatch(JSON.java:107)
05-02 14:34:40.627: W/System.err(10261): at org.json.JSONObject.<init>(JSONObject.java:158)
05-02 14:34:40.627: W/System.err(10261): at org.json.JSONObject.<init>(JSONObject.java:171)
Whats the reason for this?please Help me
Response is not a JSON object ,it's a JSON array with one element.
JSONArray a = new JSONArray("[{your JSON code}]");
JSONObject = a.getJSONObject(1);
In the following line, 'data' returns a JSON Array not a String. (Since it is enclosed in [])
jObject = new JSONObject(jObject.getString("data"));
So you'll need to get the jsonArray first.
JSONArray jArray = jObject.getJSONArray("data");
Then get the first object from the array.
JSONObject dataObject = jArray.getJSONObject(0);
now fetch the String.
String pushStatus = dataObject.getString("push_status");
Related
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();
}
I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.
This question already has answers here:
Parsing JSON Object in Java [duplicate]
(5 answers)
Closed 8 years ago.
I am retrieving JSON data and store it in array for using.
I get the json data by:-
Uri uri = new Uri.Builder().scheme("http").authority().path().build();
System.out.println("uri of category is : -"+uri);
URI u = new URI(uri.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(u);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
but my json is some other type. so i am confuse how to get and store in my arraylist.
{
employee: [
{
name: "ajay",
id: 1,
},
{
name: "rajiv",
id: 2,
}
],
address: [
{
city: "bombay",
pin: 114141
}
]
}
I know that there is first JSONObject and having two jsonarray. but how can i retrive it.
JSONArray jsonArray = jObject.getJSONArray("employee");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
modelJSon.setname(jsonObject.getString("name"));
modelJSon.setid(jsonObject.getString("id"));
modelList.add(modelJSon);
modelJSon = new ModelBroker();
}
JSONArray jsonArray = jObject.getJSONArray("address");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
modelJSon.setcity(jsonObject.getString("city"));
modelJSon.setpin(jsonObject.getString("pin"));
modelList.add(modelJSon);
modelJSon = new ModelBroker();
}
JSONObject json = new JSONObject(String jsonString);
JSONArray employeesArray = json.getJSONArray("employee");
final int arrayLength = employeesArray.length();
for (int i = 0; i< arrayLength; i++) {
JSONObject employeeJson = array.getJSONObject(i);
// parse employee JSON and add it to your ArrayList
}
Do likewise with the other array.
You can use this
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("employee");
JSONObject jo;
for(int i=0;i<jArray.length();i++){
jo = jArray.getJSONObject(i);
Log.d("name", jo.getString("name"));
Log.d("id", jo.getString("id"));
}
jArray = jObject.getJSONArray("address");
for(int i=0;i<jArray.length();i++){
jo = jArray.getJSONObject(i);
Log.d("city", jo.getString("city"));
Log.d("pin", jo.getString("pin"));
}
this is my code below how do i acess this json file check my method it is coreect method to aces json file array and nodes? i want to acess this json file below from my code help me how do i acess this json file formmy code? i dontknow howmany array in json file
{
"status":1,
"message":"",
"data":
{
"school":
[
{
"id":3,
"name":"FG Public School"
},
{
"id":4,
"name":"Fazaia Inter College"}
]
}
}
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(SelectMenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream =
response.getEntity().getContent();
BufferedReader in = new BufferedReader(new
InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object =
data.getJSONObject(i);
// JSONObject category =
object.getJSONObject("Category");
Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("name"));
Log.d("Category name",
Category_name.get(i));
Try This Code
=================================================================
try {
String[] Id,name;
JSONObject json = new JSONObject(str);
JSONObject SubString3 = json.getJSONObject("data");
Log.e(SubString3.toString(),"SubString3");
JSONArray Array = SubString3.getJSONArray("school");
Id = new String[Array.length()];
name =new String[Array.length()];
for(int i=0;i<=Array.length();i++)
{
Id[i]= Array.getJSONObject(i).getString("id");
Log.e(Id[i].toString(),"Id[i]");
name[i]= Array.getJSONObject(i).getString("name");
Log.e(name[i].toString(),"name[i]");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Category object is not present inside the Json file
you can try following
JSONObject json = new JSONObject("str");
JSONObject data = json.getJSONObject("data");
JSONArray school = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object = school.getJSONObject(i);
long id = Long.parseLong(object.getString("id"));
String name = object.getString("name");
JSONObject category = new JSONObject();
category.put("id");
category.put("name");
}
First you need to fetch an OBJECT of the whole JSON because it's in '{' '}'. Then you need to fetch an object again with the name "data" because it is in '{' '}'. And only then should you fetch the array named "school".
JSONObject json = new JSONObject(str);
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("school");
Hi I am new to working on JSON Format Webservices .
I have the Json like....
{ "meta":{"success":1},
"Countries":
[[{"Id":"1","Name":"Gibraltar",
"Cities":
[[{"Id":"21","Name":"Gibraltar"}]]
},
{"Id":"2","Name":"Canada",
"Cities":
[[{"Id":"22","Name":"Toronto"},
{"Id":"39","Name":"Banff"}]]
},
{"Id":"4","Name":"Malta",
"Cities":
[[{"Id":"37","Name":"Valletta"}]]
},
{"Id":"51","Name":"Italy",
"Cities":
[[{"Id":"24","Name":"Sardinia"}]]
},
{"Id":"53","Name":"England",
"Cities":
[[{"Id":"23","Name":"London"},
{"Id":"38","Name":"Guildford"},
{"Id":"43","Name":"Petersfield"},
{"Id":"44","Name":"Isle of Wight"}]]
},
{"Id":"175","Name":"Hungary",
"Cities":
[[{"Id":"36","Name":"Budapest"}]]
}
]]
}
But I am unable to get the values .. while parsing as json Object.
I have tried to get the values like...
public class JSONParsing1 extends ListActivity {
private static String url = "http://wsapi.vr2020.com/countries.json";
private static final String TAG_META = "meta";
private static final String TAG_SUCCESS = "success";
private static final String TAG_COUNTRIES = "Countries";
private static final String TAG_ID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_CITY = "Cities";
private static final String TAG_CITY_ID = "Id";
private static final String TAG_CITY_NANE = "Name";
private String id;
private String name;
private String city_id;
private String city_name;
JSONObject meta;
JSONArray Countries = null;
JSONArray Cities = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
try {
meta = jsonObject.getJSONObject(TAG_META);
TextView startText = (TextView) findViewById(R.id.stat_textView);
startText.setText(meta.getString(TAG_SUCCESS));
} catch (Exception e) {
e.printStackTrace();
}
try {
Countries = meta.getJSONArray(TAG_COUNTRIES);
for (int i = 0; i < Countries.length(); i++) {
JSONObject obj = Countries.getJSONObject(i);
id = obj.getString(TAG_ID);
name = obj.getString(TAG_NAME);
JSONArray city = obj.getJSONArray(TAG_CITY);
for(int j = 0; j< city.length(); j++){
JSONObject cityobj = city.getJSONObject(j);
city_id = cityobj.getString(TAG_CITY_ID);
city_name = cityobj.getString(TAG_CITY_ID);
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, list,
R.layout.list_items, new String[] { TAG_ID, TAG_NAME,
}, new int[] { R.id.id_textView,
R.id.name_textView, R.id.description_textView });
setListAdapter(adapter);
}
}
And JSON PArser Class is
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jsonObject;
}
}
Can any one share how to Parse the above JSON?
Thanks in advance.
Parse Current Json as:
JSONObject jsonObj = new JSONObject(jsonStr);
// these 2 are strings
JSONObject c = jsonObj.getJSONObject("meta");
String success = c.getString("success");
JSONArray jsonarr = jsonObj.getJSONArray("Countries");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < jsonarr.length(); i++) {
JSONArray jsonarra = jsonarr.getJSONArray(i);
// lets loop through the JSONArray and get all the items
for (int j = 0; j < jsonarra.length(); j++) {
JSONObject jsonarrtwo = jsonarra.getJSONObject(j);
// these 2 are strings
String str_id = jsonarrtwo.getString("id");
String str_Name = jsonarrtwo.getString("Name");
JSONArray jsonarr_cities = jsonarrtwo.getJSONArray("Cities");
// lets loop through the JSONArray and get all the items
for (int t = 0; t < jsonarr_cities.length(); t++) {
// printing the values to the logcat
JSONArray jsonarr_cities_one = jsonarrtwo.getJSONArray(t);
for (int tt = 0; tt < jsonarr_cities_one.length(); tt++) {
// printing the values to the logcat
JSONObject jsonarr_cities_two = jsonarr_cities_one.getJSONObject(tt);
// these 2 are strings
String str_idone = jsonarr_cities_two.getString("id");
String str_Nameone = jsonarr_cities_two.getString("Name");
}
}
}
}
for parsing json try this tuts:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
for formatting json :
http://jsonviewer.stack.hu/
You can validate your json string by this tool http://jsonlint.com/
Your json string contains a json array of json array at the Countries tag and Cities tag.
Try something like this in your JSONParsing1 activity;
replace the line of code,
Countries = meta.getJSONArray(TAG_COUNTRIES);
with this line
Countries = new JSONArray(jsonObject.getJSONArray(TAG_COUNTRIES).toString());
replace the line of code,
JSONArray city = obj.getJSONArray(TAG_CITY);
with this line
JSONArray city = new JSONArray(obj.getJSONArray(TAG_CITY).toString());
It may help you to solve the problem. Try this way... ;)