complex Json Parsing in Android - android

In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance

Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.

I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}

Related

Combining nested json for loop

I have two forloop in which the data is added to different ArrayList. Now my question is how do we combine these two arraylist?
Below is the code which i tried, but not working. Please give me solution for the same. TIA
try {
JSONObject object = new JSONObject(response);
status = object.getString("status");
if (status.equals("200")) {
rest.dismissProgressdialog();
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
New_Service_Model_1 new_service_model = new New_Service_Model_1();
new_service_model.setMain_name(jsonObject.getString("main_name"));
new_service_model.setSmid(jsonObject.optInt("smid"));
JSONArray jsonArray1 = jsonObject.getJSONArray("sub_service");
//sub_services_list.clear();
sub_services_list = new ArrayList<>();
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
New_Sub_Service_Model_1 sub_service_model = new New_Sub_Service_Model_1();
sub_service_model.setSmid(jsonObject1.optString("smid"));
sub_service_model.setSbid(jsonObject1.optInt("sbid"));
sub_service_model.setSub_name(jsonObject1.optString("sub_name"));
sub_service_model.setDesc(jsonObject1.optInt("desc"));
sub_service_model.setSt_cust(jsonObject1.optInt("st_cust"));
sub_service_model.setSt_pro(jsonObject1.optInt("st_pro"));
sub_service_model.setExist_cust(jsonObject1.optInt("exist_cust"));
sub_service_model.setExist_prov(jsonObject1.optInt("exist_prov"));
sub_services_list.add(sub_service_model);
}
new_service_model.setSub_service_list(sub_services_list);
services_list.add(new_service_model);
service_list_adapter = new Service_List_Adapter_1(this, services_list, service_costMain_interface);
rclyrview_services.setAdapter(service_list_adapter);
service_list_adapter.notifyDataSetChanged();
}
} else {
rest.dismissProgressdialog();
Toast.makeText(Service_Manage.this, "No Data found", Toast.LENGTH_SHORT).show();
}
Instead of parsing the json response manually.
Paste you json here http://www.jsonschema2pojo.org/ and use GSON or Jackson whichever is convenient for parsing the response.
There are many tutorials available which can give you a quick overview of how things can be done. Worth a try if your app has many places where you want to have Json parsing.

Android Studio Volley JSON REST API Parsing

Writing Android Application, Need to Parse JSON Data which is nested
Below is Actual data received from http.
Currently using Volley,
JSONArray dataJSONArray = response.getJSONArray("data");
Need example code to parse and display data from below mentioned JSON data
{"data":[{"counting_area_id":3,"name":"Utilization","parking_area_id":1, "free":3,"total":200,"location_latitude":null,"location_longitude":null,"places":10,
"children":[{"counting_area_id":1,"name":"Basement 1","parking_area_id":1, "free":0,"total":116,"location_latitude":null,"location_longitude":null,"places":0,
"children":[]},{"counting_area_id":73,"name":"Basement 2","parking_area_id":1, "free":3,"total":121,"location_latitude":null,"location_longitude":null,"places":3,
"children":[]}]}]}
You need to passed your data to JSONArray and parse through it using for loop ,like below code :
JSONArray jsonArray = response.getJSONArray("data");//getting array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject= jsonArray.getJSONObject(i);//getting first element
String id= jsonobject.getString("counting_area_id");//value of counting_area_id ,get all value in same way i.e location,places etc.
System.out.println(id);
JSONArray jsonObject1= object.getJSONArray("children"); //getting children array
for (int j = 0; j < jsonObject1.length(); j++) {
JSONObject object1 = jsonObject1.getJSONObject(j);
String id= object1.getString("counting_area_id");//same as before
}
}

I am trying to parse through a json could some one help me

I excuted the followinf api request
https://api-v3.mbta.com/predictions?sort=arrival_time&filter%5Bstop%5D=70028%2C70029
and I am having the following parsing problem.
Failed to parse JSON
org.json.JSONException: Value [{"attributes":{"arrival_time":"2018-04-25T13:20:01-04:00","departure_time":"2018-04-25T13:20:01-04:00",
"direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null}
,"id":"prediction-36315805-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":
{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315805","type":"trip"}}},"type":"prediction"},{"attributes"
:{"arrival_time":"2018-04-25T13:26:03-04:00","departure_time":"2018-04-25T13:26:03-04:00","direction_id":0,"schedule_relationship":null,
"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315802-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315802","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:29:28-04:00","departure_time":"2018-04-25T13:29:28-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315806-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315806","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:33:00-04:00","departure_time":"2018-04-25T13:33:00-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315803-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315803","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:36:20-04:00","departure_time":"2018-04-25T13:36:20-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315807-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315807","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:44:44-04:00","departure_time":"2018-04-25T13:44:44-04:00","direction_id":0,"schedule_relationship":"ADDED","status":null,"stop_sequence":50,"track":null},"id":"prediction-ADDED-1524238424-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"ADDED-1524238424","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:00-04:00","departure_time":"2018-04-25T13:52:00-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315809-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315809","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:39-04:00","departure_time":"2018-04-25T13:52:39-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315757-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315757","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:00:20-04:00","departure_time":"2018-04-25T14:00:20-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315758-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315758","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:09:34-04:00","departure_time":"2018-04-25T14:09:34-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315810-70029-140","relationships":{"route":{"data":{"id":"
I am parsing the code like this
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
throws IOException, JSONException {
JSONObject photosJsonObject = jsonBody.getJSONObject("data");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("attributes");
for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);
GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("arrival_time"));
item.setCaption(photoJsonObject.getString("departure_time"));
item.setUrl(photoJsonObject.getString("departure_time"));
items.add(item);
}
}
could some one tell me where I am making a mistake when parsing the object.
thank you
Well, from your posted json data is an array and attributes is an object, you were trying to parse them the other way around. Try this:
JSONArray data = jsonBody.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject singleData = data.getJSONObject(i);
JSONObject attributes = singleData.getJSONObject("attributes");
GalleryItem item = new GalleryItem();
item.setId(attributes.getString("arrival_time"));
item.setCaption(attributes.getString("departure_time"));
item.setUrl(attributes.getString("departure_time"));
items.add(item);
}
As data is a JSONArray, and your photosJsonObject should be JSONArray not object, which contains the objects. Rest is ok I think.

Json data extracting in android

i want to extract the given json arry in android,
[{"Outofserviceday":{"outofservice":"2013-02-22"}},
{"Outofserviceday":{"outofservice":"2013-02-27"}},
{"Outofserviceday":{"outofservice":"2013-02-28"}}]
i have the code for extracting the json data like given below
[{"Requestcard":{"id":"994","userprofile_id":"14","userprofile_name":"Syed
Imran","company_name":"DLF Akruti Park, Hinjewadi, Pune,
Maharashtra","sex":"male","travel_date":"2013-02-12"}}]
in this case we can retrive the json boject using the code
JSONObject menuObject = json_data.getJSONObject("Requestcard");
and retrieve each element by
requestid= menuObject.getString("id");
But in the first case how we identify each Outofserviceday in the json array ? and How extract each data ???
you can do something like below, can create jsonArray from string json data and then can extracts json objects in a loop or so.
String json =" [{\"Outofserviceday\":{\"outofservice\":\"2013-02-22\"}}]"; //json-data which is basically a json array
JSONArray jArray = new JSONArray(json); / creating an jsonarray
for (int i = 0; i < jArray.length(); i++) {
// you can have jsonObject from json array here in the loop
}
Try this:
JSONObject json = new JSONObject(result);
JSONArray json1= json.getJSONArray("data");
if (json1.length()!=0) {
for (int i = 0; i < json1.length(); i++) {
String name = json1.getJSONObject(i).getString("name");
}
}
With the help of below code you can retrieve the value of outofservice
JSONArray jArray = new JSONArray(your data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOutOfServiceDay = jArray.getJSONObject(i);
JSONObject jobj = jOutOfServiceDay.getJSONObject("Outofserviceday");
Log.i("Required data is:", "" + jobj.getString("outofservice"));
}

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources