Combining nested json for loop - android

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.

Related

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 Array Displaying only last element Android TextView

I am trying to list the JSON array and display in the TextViews, but somehow it shows only last element of the JSON array, please suggest the solution, here is my code.
JSONObject jObj = new JSONObject(response);
JSONObject jsonData = jObj.getJSONObject("data");
JSONArray jsonarr = jsonData.getJSONArray("order_status_list");
for (int i1 = 0; i1 < jsonarr.length(); i1++) {
JSONObject c1 = jsonarr.getJSONObject(i1);
txt_order_datetime.setText(c1.optString("status_datetime"));
txt_order_status.setText(c1.optString("order_status_value"));
txt_order_updatedby.setText(c1.optString("status_updated_by_user"));
}
Thanks
As suggested by #sector11, you can use
txt_order_datetime.append(c1.optString("status_datetime"));

How to split this kind of data in android

Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}

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

complex Json Parsing in 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");
}
}

Categories

Resources