I have an error when retrieving json data with retrofit2 in Android Studio. Last time i was try to retrieving data with json only 1 Response model, but now i just need to retrieving json data more than 1 table from database.
Error
java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 20 path $.pesan
No adapter attached; skipping layout
My ResponseModel.class
public class ResponseModel {
String kode, pesan;
List<QuestionModel> result_question; //But the problem is coming when i try to retrieving another json from another table(2)
List<UserDataModel> result; //i was success with this(1)
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<QuestionModel> getResult_question() {
return result_question;
}
public void setResult_question(List<QuestionModel> result_question) {
this.result_question = result_question;
}
public List<UserDataModel> getResult() {
return result;
}
public void setResult(List<UserDataModel> result) {
this.result = result;
}
}
My QuestionModel.class
public class QuestionModel {
String id_question, id_user, judul, waktu, tanggal, jml_like, aktif;
public String getId_question() {
return id_question;
}
public void setId_question(String id_question) {
this.id_question = id_question;
}
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJml_like() {
return jml_like;
}
public void setJml_like(String jml_like) {
this.jml_like = jml_like;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
My ApiRequest
#GET(url_question_list)
Call<ResponseModel> getQuestionData();
Enqueu
getData.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
pd.dismiss();
Log.d(TAG,"onResponse: "+ response.body().getKode());
mList = response.body().getResult_question();
mAdapter = new AdapterQuestion(MainActivity.this, mList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
pd.dismiss();
Log.e(TAG, "onFailure: "+t.getMessage());
}
});
JSON Format
{
"kode": 1,
"pesan": [
{
"id_question": "2",
"id_user": "8",
"judul": "Title1",
"waktu": "11:22:10",
"tanggal": "20-06-2018",
"jml_like": "0",
"aktif": "Y"
},
{
"id_question": "1",
"id_user": "9",
"judul": "Title2",
"waktu": "11:22:20",
"tanggal": "19-02-2012",
"jml_like": "1",
"aktif": "Y"
}
]
}
Thank for your help.
UPDATE: SOLVED
'Pesan' should be List<>
In your ResponseModel you define String pesan, while in the json file pesan is a List<QuestionModel>
make some changes in response model class like below ..
public class Response {
#SerializedName("kode")
private Integer kode;
#SerializedName("pesan")
private List<Pesan> pesan = null;
public Integer getKode() {
return kode;
}
public void setKode(Integer kode) {
this.kode = kode;
}
public List<Pesan> getPesan() {
return pesan;
}
public void setPesan(List<Pesan> pesan) {
this.pesan = pesan;
}
}
and also make one pesan pojo class.
public class Pesan {
#SerializedName("id_question")
private String idQuestion;
#SerializedName("id_user")
private String idUser;
#SerializedName("judul")
private String judul;
#SerializedName("waktu")
private String waktu;
#SerializedName("tanggal")
private String tanggal;
#SerializedName("jml_like")
private String jmlLike;
#SerializedName("aktif")
private String aktif;
public String getIdQuestion() {
return idQuestion;
}
public void setIdQuestion(String idQuestion) {
this.idQuestion = idQuestion;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJmlLike() {
return jmlLike;
}
public void setJmlLike(String jmlLike) {
this.jmlLike = jmlLike;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
above code working only you provide json format in question if any error then pl provide full json from server given response.
because answer is based on question json format based.
Related
I'm very new in Android and Java Programming and currently developing my skill.
now, i faced a problem with accessing Arraylist from JSONresponse.
It's just i don't know how to initiate my Variable based on Json nested object, and access it without setting it to recylerview etc.
so this is the JSON
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
ResponseModel class
public class ResponseModel {
private int kode;
private String pesan,sql;
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
ResponseModel class
public class DataModel {
private int Id_Perizinan, Id_Ortu;
private String NamaLengkapSantri, NamaLengkapOrtu, Alasan_Izin, Tgl_Pengajuan,
Durasi_Izin, Tgl_Kembali;
public int getId_Perizinan() {
return Id_Perizinan;
}
public void setId_Perizinan(int id_Perizinan) {
Id_Perizinan = id_Perizinan;
}
public int getId_Ortu() {
return Id_Ortu;
}
public void setId_Ortu(int id_Ortu) {
Id_Ortu = id_Ortu;
}
public String getNamaLengkapSantri() {
return NamaLengkapSantri;
}
public void setNamaLengkapSantri(String namaLengkapSantri) {
NamaLengkapSantri = namaLengkapSantri;
}
public String getNamaLengkapOrtu() {
return NamaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
NamaLengkapOrtu = namaLengkapOrtu;
}
public String getAlasan_Izin() {
return Alasan_Izin;
}
public void setAlasan_Izin(String alasan_Izin) {
Alasan_Izin = alasan_Izin;
}
public String getTgl_Pengajuan() {
return Tgl_Pengajuan;
}
public void setTgl_Pengajuan(String tgl_Pengajuan) {
Tgl_Pengajuan = tgl_Pengajuan;
}
public String getDurasi_Izin() {
return Durasi_Izin;
}
public void setDurasi_Izin(String durasi_Izin) {
Durasi_Izin = durasi_Izin;
}
public String getTgl_Kembali() {
return Tgl_Kembali;
}
public void setTgl_Kembali(String tgl_Kembali) {
Tgl_Kembali = tgl_Kembali;
}
and this is how I try to retrieve the data
public void loginAplikasi(){
APIRequestData apiRequestData = RetroServer.koneksiRetrofit().create(APIRequestData.class);
Call<ResponseModel> loginApp = apiRequestData.ardLogin(username,password);
loginApp.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
listData = response.body().getData();
int Id_Ortu = 0;
String NamaLengkapOrtu;
alertDialog(NamaLengkapOrtu);
} else {
alertDialog(pesan);
}
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
alertDialog(t.getMessage());
}
});
}
i successfully catched 'kode' and 'pesan' From JSON by using
int kode = response.body().getKode();
String pesan = response.body().getPesan();
i've declared a listData as new arraylist
List<DataModel> listData = new ArrayList<>();
however, how can i access the value of
listData = response.body().getData();
which contained array inside of data
so i can initiate variable ( NamaLengkapOrtu = listdata(arrayIndex) )
Thanks in advance.
The issue with DataModel class.
public class DataModel {
#SerializedName("Id_Ortu")
#Expose
private String idOrtu;
#SerializedName("NamaLengkapOrtu")
#Expose
private String namaLengkapOrtu;
public String getIdOrtu() {
return idOrtu;
}
public void setIdOrtu(String idOrtu) {
this.idOrtu = idOrtu;
}
public String getNamaLengkapOrtu() {
return namaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
this.namaLengkapOrtu = namaLengkapOrtu;
}
}
Then you can access data as follows:
String namaLengkapOrtu = listdata.get(index).getNamaLengkapOrtu();
String idOrtu = listdata.get(index).getIdOrtu();
As your JSON response is:
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
Use the below annotation in your model class:
#SerializedName("data")
#Expose
Here, "data" is the key you want to get from JSON.
Try to use this ResponseModel class:
public class ResponseModel {
private int kode;
private String pesan,SQL;
#SerializedName("data")
#Expose
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
I stuck at this problem with Post Request, which gives me error 400 bad request, i have checked the JSON RequestBody via okHttpInterceptor by Retrofit and Json validated correctly. I don't know what's the problem with requestBody. it works with ModelAttribute though, but i want to pass data as requestBody.
This is my Spring Controller ->
#RequestMapping(value = "/updateProfile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public BasicResponse farmerUpdateProfile(#RequestBody UpdateFarmerRequest updateFarmerRequest, HttpServletRequest request) {
BasicResponse response = new BasicResponse();
// get authentication token and farmer ID from header
String requestAuthToken = (String) request.getHeader(MOBILE_AUTH);
String requestFarmerId = (String) request.getHeader(FARMER_ID);
// update farmer data, if id and AuthTokens are same...
// Validate Authentication Token
try {
if (!farmerMobileManager.validateAuthToken(requestFarmerId, requestAuthToken)) {
response.setErrorCode(ErrorCode.BAD_CREDENTIALS);
response.setResponse("Bad request error");
return response;
}
farmerMobileManager.updateFarmerRequest(updateFarmerRequest, response, requestFarmerId);
} catch (Exception ex) {
System.out.println(ex.getMessage());
response.setErrorCode(ErrorCode.INTERNAL_SERVER_ERROR);
response.setResponse("Error fetching prescriptions");
}
return response;
}
This is my UpdateFarmerRequestClass.
public class UpdateFarmerRequest {
#JsonProperty("farmer")
private Farmer farmer;
public void setFarmer(Farmer farmer) {
this.farmer = farmer;
}
public Farmer getFarmer() {
return farmer;
}
}
This is my Farmerclass ->
public class Farmer extends User {
private String farmerReferenceId;
private String cropId;
private String nomineeName;
private NomineeRelation nomineeRelation;
private String stateName;
private String mandalName;
private String villageName;
private String houseNumber;
private Boolean smartPhoneUser;
private SocialStatus socialStatus;
private EducationLevel educationLevel;
private String aadharNumber;
private String stateId;
private String districtId;
private String mandalId;
private String villageId;
private Boolean oneTimeDataEntered = false;
private ArrayList<CropData> cropData;
public String getHouseNumber() {
return houseNumber;
}
public String getCropId() {
return cropId;
}
public void setCropId(String cropId) {
this.cropId = cropId;
}
public List<CropData> getCropData() {
return cropData;
}
public void setCropData(List<CropData> cropData) {
List<CropData> newCropData = new ArrayList<>();
for (CropData cropDataItem : cropData) {
Boolean didFind = false;
for (CropData farmerCropData : this.cropData) {
// if it matched in db, update the record.
if (farmerCropData.getCrop().name().equals(cropDataItem.getCrop().name())) {
// update that you got the db record
didFind = true;
farmerCropData.setCropAcres(cropDataItem.getCropAcres());
farmerCropData.setCropName(cropDataItem.getCropName());
farmerCropData.setCropYield(cropDataItem.getCropYield());
}
}
if (!didFind) {
// if you didn't fnd the record, add to new crop data
newCropData.add(cropDataItem);
}
this.cropData.addAll(newCropData);
}
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Farmer() {
super();
}
public String getNomineeName() {
return nomineeName;
}
public void setNomineeName(String nomineeName) {
this.nomineeName = nomineeName;
}
public NomineeRelation getNomineeRelation() {
return nomineeRelation;
}
public void setNomineeRelation(NomineeRelation nomineeRelation) {
this.nomineeRelation = nomineeRelation;
}
public String getMandalName() {
return mandalName;
}
public void setMandalName(String mandalName) {
this.mandalName = mandalName;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public Boolean getSmartPhoneUser() {
return smartPhoneUser;
}
public void setSmartPhoneUser(Boolean smartPhoneUser) {
this.smartPhoneUser = smartPhoneUser;
}
public SocialStatus getSocialStatus() {
return socialStatus;
}
public void setSocialStatus(SocialStatus socialStatus) {
this.socialStatus = socialStatus;
}
public EducationLevel getEducationLevel() {
return educationLevel;
}
public void setEducationLevel(EducationLevel educationLevel) {
this.educationLevel = educationLevel;
}
public String getAadharNumber() {
return aadharNumber;
}
public void setAadharNumber(String aadharNumber) {
this.aadharNumber = aadharNumber;
}
public String getFarmerReferenceId() {
return farmerReferenceId;
}
public void setFarmerReferenceId(String farmerReferenceId) {
this.farmerReferenceId = farmerReferenceId;
}
public String getStateId() {
return stateId;
}
public void setStateId(String stateId) {
this.stateId = stateId;
}
public String getDistrictId() {
return districtId;
}
public void setDistrictId(String districtId) {
this.districtId = districtId;
}
public String getMandalId() {
return mandalId;
}
public void setMandalId(String mandalId) {
this.mandalId = mandalId;
}
public String getVillageId() {
return villageId;
}
public void setVillageId(String villageId) {
this.villageId = villageId;
}
public Boolean getOneTimeDataEntered() {
return oneTimeDataEntered;
}
public void setOneTimeDataEntered(Boolean oneTimeDataEntered) {
this.oneTimeDataEntered = oneTimeDataEntered;
}
public List<String> collectErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
// if (StringUtils.isEmpty(this.nomineeName)) {
// errors.add("nomineeName");
// }
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public List<String> collectSignUpErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public static class Constants extends User.Constants {
public static final String FARMER_REFERENCE_ID = "farmerReferenceId";
public static final String AADHAR_NUMBER = "aadharNumber";
public static final String MANDAL_ID = "mandalId";
public static final String VILLAGE_ID = "villageId";
public static final String FARMER_ID = "_id";
}
}
this is my RequestBody that i am sending in POSTMAN.
RequestBody ->
{
"farmer": {
"city": "",
"mandalName": "",
"stateName": "",
"villageName": "",
"countryCode": "+",
"cropData": [{
"crop": "RICE",
"cropAcres": 1.0,
"cropName": "RICE",
"cropYield": 2.0
}, {
"crop": "PADDY",
"cropAcres": 4.0,
"cropName": "PADDY",
"cropYield": 5.0
}
],
"cropId": "",
"districtId": "",
"farmerReferenceId": "",
"firstName": "",
"houseNumber": "",
"id": "",
"mandalId": "",
"phoneNumber": "",
"stateId": "",
"villageId": ""
}
}
The Data are not empty, but i am purposely not filling it for privacy purpose.
I have solved my problem, it was naming convention problem, as i was passing cropData as "cropData", while at server Side it was "CropData."
I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I have problem with this constructor TblPemohon in class entity.TblPemohon cannot applied to given types.
I'm using Netbeans 7.0.1
The code for entity.TblProblem:
public class TblPemohon {
private String KtpPemohon;
private String NamaDepanPemohon;
private String NamaBelakangPemohon;
private String TempatLahirPemohon;
private String TanggalLahirPemohon;
private String JenisKelamin;
private String AgamaPemohon;
private String StatusPerkawinan;
private String PekerjaanPemohon;
private String NamaJalanPemohon;
private String NoAlamatPemohon;
private String RtPemohon;
private String RwPemohon;
private String KelurahanPemohon;
private String KecamatanPemohon;
private String KabupatenPemohon;
private String ProvinsiPemohon;
private String KodePosPemohon;
private String TelpPemohon;
private String KewarganegaraanPemohon;
private String errorCode;
public TblPemohon() {
}
public String getKtpPemohon() {
return KtpPemohon;
}
public void setKtpPemohon(String KtpPemohon) {
this.KtpPemohon = KtpPemohon;
}
public String getNamaDepanPemohon() {
return NamaDepanPemohon;
}
public void setNamaDepanPemohon(String NamaDepanPemohon) {
this.NamaDepanPemohon = NamaDepanPemohon;
}
public String getNamaBelakangPemohon() {
return NamaBelakangPemohon;
}
public void setNamaBelakangPemohon(String NamaBelakangPemohon) {
this.NamaBelakangPemohon = NamaBelakangPemohon;
}
public String getTempatLahirPemohon() {
return TempatLahirPemohon;
}
public void setTempatLahirPemohon(String TempatLahirPemohon) {
this.TempatLahirPemohon = TempatLahirPemohon;
}
public String getTanggalLahirPemohon() {
return TanggalLahirPemohon;
}
public void setTanggalLahirPemohon(String TanggalLahirPemohon) {
this.TanggalLahirPemohon = TanggalLahirPemohon;
}
public String getJenisKelamin() {
return JenisKelamin;
}
public void setJenisKelamin(String JenisKelamin) {
this.JenisKelamin = JenisKelamin;
}
public String getAgamaPemohon() {
return AgamaPemohon;
}
public void setAgamaPemohon(String AgamaPemohon) {
this.AgamaPemohon = AgamaPemohon;
}
public String getStatusPerkawinan() {
return StatusPerkawinan;
}
public void setStatusPerkawinan(String StatusPerkawinan) {
this.StatusPerkawinan = StatusPerkawinan;
}
public String getPekerjaanPemohon() {
return PekerjaanPemohon;
}
public void setPekerjaanPemohon(String PekerjaanPemohon) {
this.PekerjaanPemohon = PekerjaanPemohon;
}
public String getNamaJalanPemohon() {
return NamaJalanPemohon;
}
public void setNamaJalanPemohon(String NamaJalanPemohon) {
this.NamaJalanPemohon = NamaJalanPemohon;
}
public String getNoAlamatPemohon() {
return NoAlamatPemohon;
}
public void setNoAlamatPemohon(String NoAlamatPemohon) {
this.NoAlamatPemohon = NoAlamatPemohon;
}
public String getRtPemohon() {
return RtPemohon;
}
public void setRtPemohon(String RtPemohon) {
this.RtPemohon = RtPemohon;
}
public String getRwPemohon() {
return RwPemohon;
}
public void setRwPemohon(String RwPemohon) {
this.RwPemohon = RwPemohon;
}
public String getKelurahanPemohon() {
return KelurahanPemohon;
}
public void setKelurahanPemohon(String KelurahanPemohon) {
this.KelurahanPemohon = KelurahanPemohon;
}
public String getKecamatanPemohon() {
return KecamatanPemohon;
}
public void setKecamatanPemohon(String KecamatanPemohon) {
this.KecamatanPemohon = KecamatanPemohon;
}
public String getKabupatenPemohon() {
return KabupatenPemohon;
}
public void setKabupatenPemohon(String KabupatenPemohon) {
this.KabupatenPemohon = KabupatenPemohon;
}
public String getProvinsiPemohon() {
return ProvinsiPemohon;
}
public void setProvinsiPemohon(String ProvinsiPemohon) {
this.ProvinsiPemohon = ProvinsiPemohon;
}
public String getKodePosPemohon() {
return KodePosPemohon;
}
public void setKodePosPemohon(String KodePosPemohon) {
this.KodePosPemohon = KodePosPemohon;
}
public String getTelpPemohon() {
return TelpPemohon;
}
public void setTelpPemohon(String TelpPemohon) {
this.TelpPemohon = TelpPemohon;
}
public String getKewarganegaraanPemohon() {
return KewarganegaraanPemohon;
}
public void setKewarganegaraanPemohon(String KewarganegaraanPemohon) {
this.KewarganegaraanPemohon = KewarganegaraanPemohon;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
and the code for another class which call it
public List<TblPemohon> getTblPemohons() {
DataBase db = new DataBase();
try {
Pemohon p = new Pemohon(db.getConnection());
return p.getTblPemohons();
} catch (Exception e) {
List<TblPemohon> ltp = new ArrayList<TblPemohon>();
ltp.add(new TblPemohon(e.getMessage()));
return ltp;
} finally {
db.close();
}
}
Your TblPemohon class only have non-argument constructor, but you tried to create it with a constructor that takes one string here:
ltp.add(new TblPemohon(e.getMessage()));
You need to either add a constructor that take one string, or use the non-argument constructor
I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Here you have a tutorial which answers your needs - Android + Gson