Android - How to get JSON array in Child - android

I'm beginner in Android Studio, and I am a bit difficult to parse json data in Android, so I want to ask question about get or parsing JSON Child Array.
This is my Code :
public void resSuccess(String requestType, JSONObject response)
{ progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONArray array = response.getJSONArray("all_airport");
for (int i=0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("airport");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
BandaraDataSet bds = new BandaraDataSet();
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}
And This is my Json
{
"all_airport":{
"airport":[
{
"airport_name":"Mali",
"airport_code":"ARD",
"location_name":"Alor Island",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Pattimura",
"airport_code":"AMQ",
"location_name":"Ambon",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Tanjung Api",
"airport_code":"VPM",
"location_name":"Ampana",
"country_id":"id",
"country_name":"Indonesia"
}
]
},
"token":"ab4f5e12e794ab09d49526bc75cf0a0139d9d849",
"login":"false"
}
so my problem when Parse Json is null in Android, please help anyone..

You are handling the JSONObject as if it were a JSONArray. Try this code:
public void resSuccess(String requestType, JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONObject airports = response.getJSONObject("all_airport");
JSONArray airportArray = airports.getJSONArray("airport");
for (int j = 0; j < airportArray.length(); j++) {
BandaraDataSet bds = new BandaraDataSet();
JSONObject object = airportArray.getJSONObject(j);
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}

You should proper json parsing or you can use Gson(library) for json parsing. You just need to have proper Model(Bean) classes. And then parsing will be too easy.
compile 'com.google.code.gson:gson:2.7'
Create below Model/Bean classes
import java.io.Serializable;
//Response.java
public class Response implements Serializable {
AllAirPort all_airport;
public AllAirPort getAll_airport() {
return all_airport;
}
public void setAll_airport(AllAirPort all_airport) {
this.all_airport = all_airport;
}
}
//AllAirPort.java
public class AllAirPort implements Serializable{
ArrayList<AirportModel> airport;
public ArrayList<AirportModel> getAirport() {
return airport;
}
public void setAirport(ArrayList<AirportModel> airport) {
this.airport = airport;
}
}
//AirportModel.java
public class AirportModel implements Serializable {
String airport_name;
String airport_code;
String location_name;
String country_id;
String country_name;
public String getAirport_name() {
return airport_name;
}
public void setAirport_name(String airport_name) {
this.airport_name = airport_name;
}
public String getAirport_code() {
return airport_code;
}
public void setAirport_code(String airport_code) {
this.airport_code = airport_code;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
}
Response responseObject = new Gson().fromJson(yourstringResponse, Response.class);
now you can start getting data from responseObject.

Related

How parse JSON data into ListView

I would like to visualize the Json data on a listview, but I don't know how to do it ... I tried to use a TextView to verify the correct passage of the data and it seems to work, but I would need to display them on the listView ... ideas?
{"Esito":true,"Dati":[{"id":"357","id_utente":"16","nome_prodotto":"cozze"},{"id":"358","id_utente":"16","nome_prodotto":"riso"},{"id":"362","id_utente":"16","nome_prodotto":"patate"},{"id":"366","id_utente":"16","nome_prodotto":"cozze"},{"id":"367","id_utente":"16","nome_prodotto":null}]}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.G[enter image description here][1]ET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
String id = dato.getString("id");
String id_utente = dato.getString("id_utente");
String nome_prodotto = dato.getString("nome_prodotto");
mTextViewResult.append(id + ", " + id_utente + ", " + nome_prodotto + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Just make new object class and collect data to list :
class YourObiekt {
private String id;
private String idUtente;
private String nomeProdotto;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdUtente() {
return idUtente;
}
public void setIdUtente(String idUtente) {
this.idUtente = idUtente;
}
public String getNomeProdotto() {
return nomeProdotto;
}
public void setNomeProdotto(String nomeProdotto) {
this.nomeProdotto = nomeProdotto;
}
}
List<YourObiekt> yourObiektList = new ArrayList<YourObiekt>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
YourObiekt yo = new YourObiekt();
yo.setId(dato.getString("id"));
yo.setIdUtente(dato.getString("id_utente"));
yo.setNomeProdotto(dato.getString("nome_prodotto"));
yourObiektList.add(yo);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And now you get yourObiektList as data for your listView

How to retrieve array in array using GET methos of volley?

Im using Rest Countries API to retrieve language data, https://restcountries.eu/rest/v2/all.. but the languages does't show up because the data was in array.
this is the code that i write to retrieve the data using Method.Get
private void getCountriesList() {
String url = "https://restcountries.eu/rest/v2/all";
StringRequest request = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.isEmpty()) {
Gson gson = new Gson();
JSONObject json = null;
// array of country
LanguageModel[] countries = gson.fromJson(response, LanguageModel[].class);
// add it to adapter
for(LanguageModel country: countries) {
mAdapter.addItem(country);
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getLocalizedMessage());
}
}
);
Volley.newRequestQueue(getApplicationContext()).add(request);
}
This is the model. the code was successful when i retrieve country name, but it was failed when i retrieve language data
public class CountryModel {
private String languages;
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}}
I got it working with the following code:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject countryObj = mainArray.getJSONObject(i);
JSONArray languageArray = countryObj.getJSONArray("languages");
List<LanguageModel> languageModels = gson.fromJson(languageArray.toString(), new TypeToken<List<LanguageModel>>() {
}.getType());
// add it to adapter
for (LanguageModel languageModel : languageModels) {
//mAdapter.addItem(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// array of country
}
Let me know if you still get the error.
Edit:
but how to get country name and language at the same time?
You have to edit your CountryModel as following:
public class CountryModel {
#SerializedName("name")
String countryName;
#SerializedName("languages")
ArrayList<LanguageModel> languages;
public CountryModel() {
}
}
And LanguageModel as following:
class LanguageModel {
#SerializedName("iso639_1")
String iso1;
#SerializedName("iso639_2")
String iso2;
#SerializedName("name")
String name;
#SerializedName("nativeName")
String nativeName;
public LanguageModel() {
}
}
Now the final change in parsing:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
List<CountryModel> countryList = gson.fromJson(mainArray.toString(), new TypeToken<List<CountryModel>>() {
}.getType());
//do something with your country list
Log.d("R-Countries", countryList.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
While this answer works you should see the following link to understand what i did here.
http://www.studytrails.com/java/json/java-google-json-introduction/

JSON parsing for an array with two arraylists inside [duplicate]

This question already has answers here:
Parsing JSON object in android
(5 answers)
Closed 4 years ago.
I am trying to parse the following API data. I just have to use the start time, end time, location and event name inside my app. I have never parse this type of data before. Hitting the API URL and getting a response is working fine, I just need help in parsing.
I have tried these solutions but it didn't work.
parsing JSON 2 arrays (embedded) in Android
How to Parsing JSON (Two Dimensional) array Object in android?
How to parse JsonArray and JSON Object having two keys and values in android?
Ask Android parsing JSON multiple arrays.
JSON:
[
{
"end": {
"endDate": "2018-03-09",
"endTime": "03:00",
"_id": "5a901a7d9fee7d156d594b04"
},
"location": "Dance Tent",
"start": {
"startDate": "2018-03-09",
"startTime": "02:00",
"_id": "5a901a7d9fee7d156d594b05"
},
"announcementName": "Jumanji Dance Party"
}
]
Code:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
String fullName = jsonObject.getString("startTime");
String about = jsonObject.getString("announcementName");
String artistType = jsonObject.getString("endTime");
String link = jsonObject.getString("location");
//String avatar = jsonObject.getString("avatar");
Annoucement_Day_One artistInfoGetter=new Annoucement_Day_One( fullName,about, artistType, link );
annoucementDayOneList.add(artistInfoGetter);
wednesdayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERRROR RES: ", error.toString());
myInstance.dismiss();
}
});
requestQueue.add(jsonArrayRequest);
Try this
try {
JSONArray jsonArray= new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String location=object.getString("location");
String announcementName=object.getString("announcementName");
JSONObject end=object.getJSONObject("end");
String endDate=end.getString("endDate");
String endTime=end.getString("endTime");
String id=end.getString("_id");
JSONObject start=object.getJSONObject("start");
String startDate=start.getString("startDate");
String startTime=start.getString("startTime");
String start_id=start.getString("_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this ,
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
JSONObject startJson = jsonObject.getJSONObject("start");
String startTime = startJson.getString("startTime");
JSONObject endJson = jsonObject.getJSONObject("end");
String endTime = endJson.getString("endTime");
String announcementName = jsonObject.getString("announcementName");
String location = jsonObject.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayList<Holder1> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
for(int index = 0 ;index < jsonArray.length() ; index++){
JSONObject jsonObject1 = jsonArray.getJSONObject(index);
//make a holder for end, location, start,announcementName
Holder1 holder = new Holder1();
holder.setLocation(jsonObject1.optString("location"));
holder.setAnnouncementName(jsonObject1.optString("announcementName"));
//------------
JSONObject jsonObjectEnd =jsonObject1.getJSONObject("end");
holder.setEndDate(jsonObjectEnd.optString("endDate"));
holder.setEndTime(jsonObjectEnd.optString("endTime"));
holder.setEndID(jsonObjectEnd.optString("_id"));
//--------------
JSONObject jsonObjectStart =jsonObject1.getJSONObject("start");
holder.setStartDate(jsonObjectStart.optString("startDate"));
holder.setStartTime(jsonObjectStart.optString("startTime"));
holder.setStartID(jsonObjectStart.optString("_id"));
//--------------
arrayList.add(holder);
}
} catch (JSONException e) {
e.printStackTrace();
}
Accept the answer. If you like the way i have written.
You can use the GSON library by google.
add the dependency in build.gradle.
compile 'com.google.code.gson:gson:2.8.0'
First, you have to create the model class for your JSON response. this will help you to create the model class.
public class MyPojo
{
private Start start;
private String location;
private String announcementName;
private End end;
public Start getStart ()
{
return start;
}
public String getLocation ()
{
return location;
}
public String getAnnouncementName ()
{
return announcementName;
}
public End getEnd ()
{
return end;
}
}
--------------Start.Java------------
public class Start
{
private String startTime;
private String startDate;
private String _id;
public String getStartTime ()
{
return startTime;
}
public String getStartDate ()
{
return startDate;
}
public String get_id ()
{
return _id;
}
}
------------End.Java-------------------
public class End
{
private String _id;
private String endDate;
private String endTime;
public String get_id ()
{
return _id;
}
public String getEndDate ()
{
return endDate;
}
public String getEndTime ()
{
return endTime;
}
}
Now in your onResponse method
MyPojo respnse = new Gson().fromJson(response.toString(), MyPojo.class);
you can access any method from response.Ex. response.getEnd().getEnd_date()

How to sort a jsonarray data by Date & Time and put in list view adapter

here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}

How can send this json to server with content type as application/x-www-form-urlencoded in android

How can I send this JSON to server API with content type as application/x-www-form-urlencoded in Android?
JSON is:
{
"id":1,
"name":"data1",
"datas":
[
{
"data_id":0,
"data_name":"data10"
},
{
"data_id":1,
"data_name":"data11"
},
{
"data_id":2,
"data_name":"data12"
}
]
}
public JSONObject buildRequestBody() {
JSONObject jsonObject = new JSONObject();
Context context = getAppContext();
if(context == null) {
return jsonObject;
}
try {
JSONObject datasJsonObject = new JSONObject();
datasJsonObject.put("id", mId);
datasJsonObject.put("name", mName);
JSONArray jsonArray = new JSONArray();
for (Datas datas : mListDatas) {
jsonArray.put(datas.getDataId());
jsonArray.put(datas.getDataName());
}
datasJsonObject.put("datas", jsonArray);
return datasJsonObject;
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
}
return jsonObject;
}
Datas.Java
public class Datas {
private double mDataId;
private String mDataName;
public double getDataId() {
return mDataId;
}
public void setDataId(double mDataId) {
this.mDataId = mDataId;
}
public String getDataName() {
return mDataName;
}
public void setDataName(String mDataName) {
this.mDataName = mDataName;
}
}

Categories

Resources