How to store info of JSON [duplicate] - android

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"));
}

Related

How to fetch json array inside array in android listview

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.

Reading Json string from a JsonObject in android [duplicate]

This question already has answers here:
JSONArray cannot be converted to JSONObject error
(3 answers)
Closed 6 years ago.
I am having problems; I cannot read inner string from a jsonObject. It says JsonArray cannot be converted into JsonObject.
07-26 13:01:31.910 1798-1901/com.example.phuluso.aafs I/System.out: [{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my JsonArray. I am trying to read from AccommoAddress, but I get the error below:
[{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my code
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
List<AccommoNearAPK> data = new ArrayList<>();
progressDialog.dismiss();
JSONObject jsonResponse = null;
try
{
jsonResponse = new JSONObject(result);
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("Street");
String number = jsonChildNode.optString("City");
String date_added = jsonChildNode.optString("Longitude");
String lat = jsonChildNode.optString("Lattitude");
System.out.print("Street"+ name + "City" +number+ "Long" + date_added+" Lat" + lat);
Toast.makeText(MapsActivity.this, date_added + name + number + lat, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(MapsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
"AccommoAddress" is a JSONObject not a JSONArray. So instead of this..
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
Try this ..
/*String Accommo = jsonResponse.getString("AccommoAddress");
JSONObject AccomoAddress = new JSONObject(Accommo);*/
//simplifying the above code
JSONObject Accomoaddress = jsonResponse.optJSONObject("AccomoAddress");
String name = AccomoAddress.getString("Street");
String number = AccomoAddress.getString("City");
String date_added = AccomoAddress.getString("Longitude");
String lat = AccomoAddress.getString("Lattitude");
Your response is a JSONArray, not a JSONObject, similarly, AccommoAddress is a JSONObject, not a JSONArray. So you need to change the lines near the top to the following:
JSONArray jsonResponse = null;
try
{
jsonResponse = new JSONArray(result);
JSONObject jsonMainNode = jsonResponse.optJSONObject("AccommoAddress");

How to get values from json webservices

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");

Unable to parse JSON values in Android

I am facing some problem while parsing JSON values, Please find the JSON file below,
{
"Account": "xxx",
"Account_desc": "xxx",
"TimeZone": "GMT+05:30",
"DeviceList": [
{
"Device": "xttt",
"Device_desc": "txtx",
"EventData": [
{
"Device": "xttt",
"Timestamp": 1373539125,
"Timestamp_date": "2013/07/11",
"Timestamp_time": "16:08:45",
"StatusCode": 61715,
"StatusCode_hex": "0xF113",
"StatusCode_desc": "Stop",
"GPSPoint": "12.97887,77.51030",
"GPSPoint_lat": 12.97887,
"GPSPoint_lon": 77.51030,
"Speed": 0.0,
"Speed_units": "km/h",
"Odometer": 3.416,
"Odometer_units": "Km",
"Geozone": "zone4",
"Geozone_index": 0,
"Address": "cxcxc",
"DigitalInputMask": 251,
"DigitalInputMask_hex": "0xFB",
"Index": 0
}
]
},
{
"Device": "pppp",
"Device_desc": "statstr",
"EventData": [
{
"Device": "pppp",
"Timestamp": 1368870217,
"Timestamp_date": "2013/05/18",
"Timestamp_time": "15:13:37",
"StatusCode": 61715,
"StatusCode_hex": "0xF113",
"StatusCode_desc": "Stop",
"GPSPoint": "14.26281,80.11421",
"GPSPoint_lat": 14.26281,
"GPSPoint_lon": 80.11421,
"Speed": 0.0,
"Speed_units": "km/h",
"Odometer": 373.874,
"Odometer_units": "Km",
"Geozone": "port",
"Geozone_index": 0,
"Address": "asdfsdfss",
"Index": 0
}
]
}
]
}
From the above JSON , I would like to have only "GPSPoint_lat","GPSPoint_lon" and "Device" in "EventData" So I did the coding as follows,
JSONObject jsonObject = ApplicationContext.getHttpService()
.readAsJson(s);
// System.out.println("indexvalue:"+s.indexOf(1,5));
// JSONObject object = jsonObject.getJSONObject("DeviceList");
JSONArray jsonArray = jsonObject.getJSONArray("DeviceList");
JSONObject object = jsonArray.getJSONObject(0);
JSONArray secondarray = object.getJSONArray("EventData");
for (int i = 0; i < secondarray.length(); i++) {
try {
System.out.println("Im...");
// System.out.println("Latitude:"+ ((JSONObject)
// jsonArray.get(i)).getString("GPSPoint_lat"));
// String id = ((JSONObject)
// jsonArray.get(i)).getString("deviceID");
// arr = (JSONArray) jsonArray.get(i);
JSONObject obj = secondarray.getJSONObject(i);
String lat = obj.getString("GPSPoint_lat");
String lon = obj.getString("GPSPoint_lon");
........//..
...///......}}
But problem in the above code is whenever I am executing I am getting the arraylength is 1, i.e., getting only one value I mean first Eventdata values. What i need in this is I would like to get all the "Eventdata" values. Please suggest me regarding this.
Regards
Priya
JSONObject object = jsonArray.getJSONObject(0);
I am guessing at this point in the above code you are just fetching the data at the first index which is specified by '0'. Hence you get the length also as one. Try doing the object.getJSONArray() inside the loop with the index. Maybe that will help you get all the data inside "EventData". Hope this helps :)
Try this..
JSONArray jsonArray = jsonObject.getJSONArray("DeviceList");
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
JSONArray secondarray = object.getJSONArray("EventData");
for (int i = 0; i < secondarray.length(); i++) {
System.out.println("Im...");
// System.out.println("Latitude:"+ ((JSONObject)
// jsonArray.get(i)).getString("GPSPoint_lat"));
// String id = ((JSONObject)
// jsonArray.get(i)).getString("deviceID");
// arr = (JSONArray) jsonArray.get(i);
JSONObject obj = secondarray.getJSONObject(i);
String lat = obj.getString("GPSPoint_lat");
String lon = obj.getString("GPSPoint_lon");
}
}
For JSON parsing use following class.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class JSONParser {
public JSONParser() {
}
JSONObject jObj;
String json;
InputStream is = null;
public JSONObject getJsonFromUrl(String url) {
// TODO Auto-generated method stub
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception 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();
System.out.println("Json String : " + json);
} catch (Exception e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
return jObj;
}
}
and in your MainActivity use following code to parse it.
JSONParser parser = new JSONParser();
JSONObject o = parser.getJsonFromUrl("yourjsonurl");
String Account = o.getString("Account");
String Account_desc = o.getString("Account_desc");
JSONArray array = o.getJSONArray("DeviceList");
JSONObject o1 = array.getJSONObject(0);
String Device = o1.getString("Device");
//Again you have JSONArray
JSONArray a = o1.getJSONArray("EventData");
//Then get object form array at index 0.
JSONObject obj = a.getJSONObject(0);
Then get your data from this json object.
The problem in your JSON is that in eventData array you have 1 JSON object with alot of mappings and not allot of jsonObjects. If you wannt EventData to be a JSONArray with all
.."Geozone": "zone4",
"Geozone_index": 0,
"Address": "cxcxc",
"DigitalInputMask": 251,
"DigitalInputMask_hex": "0xFB",
"Index": 0...
as JsonObject you need yo change the JSON to be as an array
..{"Geozone": "zone4"},
{"Geozone_index": 0},
{"Address": "cxcxc"},
{"DigitalInputMask": 251},
{"DigitalInputMask_hex": "0xFB"},
{ "Index": 0}
...
JSONArray DeviceListArray = jsonObject.getJSONArray("DeviceList");
for (int i = 0; i < DeviceListArray.length(); i++) {
JSONObject Deviceobject = DeviceListArray.getJSONObject(i);
JSONArray EventDataArray = Deviceobject.getJSONArray("EventData");
for (int j= 0; j < EventDataArray.length(); j++) {
JSONObject valueObj = EventDataArray.getJSONObject(j);
String GPSPoint_lat = valueObj.getString("GPSPoint_lat");
String GPSPoint_lon = valueObj.getString("GPSPoint_lon");
String Device = valueObj.getString("Device");
// Store this three values in ArrayList
}
}
}
Priya, Your json contains three objects and two arrays as follows
Objects
1. Entire response
2. DeviceList
3. EventData
Arrays
Device List - holds arrays of devices
Event Data - Arrays of events
Now carefully look your JSON, that json contains N number of Devices but every device has one event, So you have to iterate DeviceList and then iterate event list.
So that iteration should as follows.
JSONObject jsonObject = ApplicationContext.getHttpService().readAsJson(s);
JSONArray jsonDeviceListArray = jsonObject.getJSONArray("DeviceList");
int deviceCount = jsonDeviceListArray.length();
JSONObject jsonDeviceObj;
JSONArray jsonEventList;
for (int deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++) {
jsonDeviceObj = jsonDeviceListArray.getJSONObject(deviceIndex);
//Here you can print device, device_desc from jsonDeviceObj
jsonEventList = jsonDeviceObj.getJSONArray("EventData");
int eventCount = jsonEventList.length();
JSONObject jsonEventObj;
for (int eventIndex = 0; eventIndex < eventCount; eventIndex++) {
jsonEventObj = jsonEventList.getJSONObject(eventIndex);
//Here you can print event info.
}
}
You have missing "" in your json data. All numbers should have "", as before parsing it is treated as string.

how to access multi array json file?

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");

Categories

Resources