json data should be print in specified textview - java

I have json data regarding student details,That i want to print in respective textviews. i'm new to json services please help me to print the this data on screen.I'm using getters and setters for subject score so further i want to use them dynamically.
here is my json data
{
"studentInfo": {
"studentName": "srini#gmail.com",
"studentId": "abc",
"date": 14102017,
"JanuaryScoreCard" : {
"english" : "44",
"Science" : "45",
"maths": "66",
"social" : "56",
"hindi" : "67",
"kannada" : "78",
},
"MarchScoreCard" : {
" english " : "54",
" Science " : "56",
" maths ": "70",
" social " : "87",
" hindi " : "98",
" kannada " : "56"
},
"comments" : ""
}
I'm Something to print but could not,i don't where i'm going wrong
public void init()
{
try {
parseJSON();
} catch (JSONException e)
{
e.printStackTrace();
}
}
public void parseJSON() throws JSONException{
jsonObject = new JSONObject(strJson);
JSONObject object = jsonObject.getJSONObject("studentInfo");
patientName = object.getString("studentName");
patientID = object.getString("studentId");
mName.setText(studentName);
mUserId.setText(studentId);
}

You can use JSON parser and then you can print any data you want from that,
Use GSON for this, here is an example https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

Here is a basic JSON Parsing process
public void parseJson() {
String your_response = "replace this with your response";
try {
JSONObject jsonObject = new JSONObject(your_response);
JSONObject studentInfoJsonObject = jsonObject.getJSONObject("studentInfo");
StudentInfo studentInfo1 = new StudentInfo();
studentInfo1.setStudentName(studentInfoJsonObject.optString("studentName"));
studentInfo1.setStudentId(studentInfoJsonObject.optString("studentId"));
studentInfo1.setDate(studentInfoJsonObject.optString("date"));
studentInfo1.setComments(studentInfoJsonObject.optString("comments"));
JSONObject januaryScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
JanuaryScoreCard januaryScoreCard1 = new JanuaryScoreCard();
januaryScoreCard1.setEnglish(januaryScoreCardJsonObject.optString("english"));
januaryScoreCard1.setHindi(januaryScoreCardJsonObject.optString("hindi"));
januaryScoreCard1.setMaths(januaryScoreCardJsonObject.optString("maths"));
januaryScoreCard1.setSocial(januaryScoreCardJsonObject.optString("social"));
januaryScoreCard1.setKannada(januaryScoreCardJsonObject.optString("kannada"));
januaryScoreCard1.setScience(januaryScoreCardJsonObject.optString("Science"));
JSONObject marchScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
MarchScoreCard marchScoreCard = new MarchScoreCard();
marchScoreCard.setEnglish(marchScoreCardJsonObject.optString("english"));
marchScoreCard.setHindi(marchScoreCardJsonObject.optString("hindi"));
marchScoreCard.setMaths(marchScoreCardJsonObject.optString("maths"));
marchScoreCard.setSocial(marchScoreCardJsonObject.optString("social"));
marchScoreCard.setKannada(marchScoreCardJsonObject.optString("kannada"));
marchScoreCard.setScience(marchScoreCardJsonObject.optString("Science"));
studentInfo1.setJanuaryScoreCard(januaryScoreCard1);
studentInfo1.setMarchScoreCard(marchScoreCard);
} catch (JSONException e) {
e.printStackTrace();
}
}
Student Info Class
public class StudentInfo {
private String studentName;
private String studentId;
private String date;
private String comments;
private JanuaryScoreCard januaryScoreCard;
private MarchScoreCard marchScoreCard;
public JanuaryScoreCard getJanuaryScoreCard() {
return januaryScoreCard;
}
public void setJanuaryScoreCard(JanuaryScoreCard januaryScoreCard) {
this.januaryScoreCard = januaryScoreCard;
}
public MarchScoreCard getMarchScoreCard() {
return marchScoreCard;
}
public void setMarchScoreCard(MarchScoreCard marchScoreCard) {
this.marchScoreCard = marchScoreCard;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
and Here is January class
public class JanuaryScoreCard {
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
and Here is March Class
public class MarchScoreCard{
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}

You need to parse this json Data , For this you need Create appropriate bean classes and put data while parsing json into this bean classes object and create List .
Then you need to create ListView and Adapter for populate data into Screen or Activity.

Related

how to get specific response data inside array response android retrofit2

Here is my response from database
{
"error": false,
"images": [
{
"id": "9",
"url": "http://192.168.1.27/BimbinganPA/include//uploads/9.png"
}
]
}
my response class UserDataResponse.java (edited full data response)
#SerializedName("error")
#Expose
private String iserror;
#SerializedName("error_msg")
#Expose
private String error_msg;
#SerializedName("nama")
#Expose
private String nama;
#SerializedName("nomor_induk")
#Expose
private String nomor_induk;
#SerializedName("prodi")
#Expose
private String prodi;
#SerializedName("dosen_pa")
#Expose
private String dosen_pa;
#SerializedName("email")
#Expose
private String email;
#SerializedName("email2")
#Expose
private String email2;
#SerializedName("mobile_phone")
#Expose
private String mobile_phone;
#SerializedName("mobile_phone2")
#Expose
private String mobile_phone2;
#SerializedName("alamat_mlg")
#Expose
private String alamat_mlg;
#SerializedName("alamat_asal")
#Expose
private String alamat_asal;
#SerializedName("sma_asal")
#Expose
private String sma_asal;
#SerializedName("hobby")
#Expose
private String hobby;
#SerializedName("ekskul")
#Expose
private String ekskul;
#SerializedName("nama_ortu")
#Expose
private String nama_ortu;
#SerializedName("alamat_ortu")
#Expose
private String alamat_ortu;
#SerializedName("email_ortu")
#Expose
private String email_ortu;
#SerializedName("mobilephone_ortu")
#Expose
private String mobilephone_ortu;
#SerializedName("id_fb")
#Expose
private String id_fb;
#SerializedName("id_ig")
#Expose
private String id_ig;
#SerializedName("id_line")
#Expose
private String id_line;
#SerializedName("numb_wa")
#Expose
private String numb_wa;
#SerializedName("images")
#Expose
private List<Image> images = null;
public String getIserror() {
return iserror;
}
public void setIserror(String iserror) {
this.iserror = iserror;
}
public String getMsg() {
return error_msg;
}
public void setMsg(String error_msg) {
this.error_msg = error_msg;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNomor_induk() {
return nomor_induk;
}
public void setNomor_induk(String nomor_induk) {
this.nomor_induk = nomor_induk;
}
public String getProdi() {
return prodi;
}
public void setProdi(String prodi) {
this.prodi = prodi;
}
public String getDosen_pa() {
return dosen_pa;
}
public void setDosen_pa(String dosen_pa) {
this.dosen_pa = dosen_pa;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public String getMobile_phone() {
return mobile_phone;
}
public void setMobile_phone(String mobile_phone) {
this.email = mobile_phone;
}
public String getMobile_phone2() {
return mobile_phone2;
}
public void setMobile_phone2(String mobile_phone2) {
this.email = mobile_phone2;
}
public String getAlamat_mlg() {
return alamat_mlg;
}
public void setAlamat_mlg(String alamat_mlg) {
this.alamat_mlg = alamat_mlg;
}
public String getAlamat_asal() {
return alamat_asal;
}
public void setAlamat_asal(String alamat_asal) {
this.alamat_asal = alamat_asal;
}
public String getSma_asal() {
return sma_asal;
}
public void setSma_asal(String sma_asal) {
this.sma_asal = sma_asal;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getEkskul() {
return ekskul;
}
public void setEkskul(String ekskul) {
this.ekskul = ekskul;
}
public String getNama_ortu() {
return nama_ortu;
}
public void setNama_ortu(String nama_ortu) {
this.nama_ortu = nama_ortu;
}
public String getAlamat_ortu() {
return alamat_ortu;
}
public void setAlamat_ortu(String alamat_ortu) {
this.alamat_ortu = alamat_ortu;
}
public String getEmail_ortu() {
return email_ortu;
}
public void setEmail_ortu(String email_ortu) {
this.email_ortu = email_ortu;
}
public String getMobilephone_ortu() {
return mobilephone_ortu;
}
public void setMobilephone_ortu(String mobilephone_ortu) {
this.mobilephone_ortu = mobilephone_ortu;
}
public String getId_fb() {
return id_fb;
}
public void setId_fb(String id_fb) {
this.id_fb = id_fb;
}
public String getId_ig() {
return id_ig;
}
public void setId_ig(String id_ig) {
this.id_ig = id_ig;
}
public String getId_line() {
return id_line;
}
public void setId_line(String id_line) {
this.id_line = id_line;
}
public String getNumb_wa() {
return numb_wa;
}
public void setNumb_wa(String numb_wa) {
this.numb_wa = numb_wa;
}
public List<Image> getImages() {
return images;
}
here is my Image.class
#SerializedName("id")
#Expose
private String no_user_id;
#SerializedName("url")
#Expose
private String image_url;
public String getNo_user_id() {
return no_user_id;
}
public String getImage_url() {
return image_url;
}
this is how i call it
public void F0_getPhoto(){
Call<List<UserDataResponse>> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<List<UserDataResponse>>() {
#Override
public void onResponse(Call<List<UserDataResponse>> call, Response<List<UserDataResponse>>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
List<UserDataResponse> userDatalist = response.body();
//Creating an String array for the ListView
String[] iserror = new String[userDatalist.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < userDatalist.size(); i++) {
iserror[i] = userDatalist.get(i).getIserror();
if (iserror.equals("false")) {
String[] url = new String[userDatalist.size()];
url[i] = userDatalist.get(i).getImages().getimage_Url();
showPhoto(url);
}
}
#Override
public void onFailure(Call<List<UserDataResponse>> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
and my question is how i can call response "url" from array i tried to call method getimage_Url() after method getImage() but i cannot call it
url[i] = userDatalist.get(i).getImages().getimage_Url();
According your above json, it's return Object rather than Array. So, modify your F0_getPhoto to handle this.
public void F0_getPhoto(){
Call<UserDataResponse> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<UserDataResponse>() {
#Override
public void onResponse(Call<UserDataResponse> call, Response<UserDataResponse>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
UserDataResponse userData = response.body();
//Creating an String array for the ListView
String error = userData.getIserror();
List<Image> images = userData.getImages();
String[] url = new String[images.size()];
//looping through all the heroes and inserting the names inside the string array
if (iserror.equals("false")) {
for (int i = 0; i < images.size(); i++) {
url[i] = images.getimage_Url();
}
showPhoto(url);
}
#Override
public void onFailure(Call<UserDataResponse> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
}

The request sent by the client was syntactically incorrect. Spring Backend

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."

How to deserialize a JSON Object in a multidimensional array

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

Model Class for the given GoogleBooks API

I am new to android and I am creating an app to learn JSON Parsing. I want to parse the Google Books API's JSON data for my app, but I am having trouble creating the Model class for the API. Here is the JSON data for the for first result displayed in the data:
{
"kind": "books#volumes",
"totalItems": 1591,
"items": [
{
"kind": "books#volume",
"id": "An4_e3Cr3zAC",
"etag": "DWmqBRkB8dw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
"volumeInfo": {
"title": "The Rules of the Game",
"authors": [
"Neil Strauss"
],
"publisher": "Canongate Books",
"publishedDate": "2011-09-29",
"description": "If you want to play The Game you need to know The Rules This book is not a story. It is a how-to book. This Stylelife Challenge is not meant to be read. It is meant to be performed. Whatever experience level you have, whatever strengths and weaknesses you may have, whether you're a virgin or a Don Juan, the stage has been set for you to perform at your highest capacity. The Stylelife Challenge is a simple, easy-to-follow guide to the basics of approaching and attracting women. The Challenge is simply what works best and fastest. Neil Strauss spent four years gathering this knowledge, living it and sharing it. He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques. The result: A month-long workout program for your social, attraction, dating and seduction skills.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781847673558"
},
{
"type": "ISBN_10",
"identifier": "1847673554"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 352,
"printType": "BOOK",
"categories": [
"Biography & Autobiography"
],
"averageRating": 3.5,
"ratingsCount": 82,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.7.6.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
},
"saleInfo": {
"country": "IN",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 399.0,
"currencyCode": "INR"
},
"retailPrice": {
"amount": 279.3,
"currencyCode": "INR"
},
"buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 3.99E8,
"currencyCode": "INR"
},
"retailPrice": {
"amountInMicros": 2.793E8,
"currencyCode": "INR"
}
}
]
},
"accessInfo": {
"country": "IN",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-epub.acsm?id=An4_e3Cr3zAC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques."
}
}
]
}
I created four Model classes (as I saw fit). Here is the code of all four classes. All the classes contains their respective setters and getters.
public class BookItems {
String kind;
String id;
String etag;
String selfLink;
}
public class BookVolumeInfo {
String title;
String publisher;
String publishedDate;
String description;
long pageCount;
float averageRating;
long ratingsCount;
String maturityRating;
}
public class BookAuthors {
String authors;
}
public class BookCategories {
String categories;
}
I want to do this all in one class if possible. And when I ran the code I am not getting the title of the book. Here is the Main code of my project.
public class MainActivity extends AppCompatActivity {
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
public static final String MyAPIKey = "Your_Api_Key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);
searchButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
// Log.e(Logcat,"URL created successfully");
// Log.i(Logcat,"URL created successfully");
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
// Log.e(Logcat,"Search field empty");
// Log.i(Logcat,"Search field empty");
}
new JSONTask().execute(urlstring);
//Toast.makeText(MainActivity.this, "Search Button Clicked.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
public class JSONTask extends AsyncTask<String, String, List<BookVolumeInfo>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BookVolumeInfo> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
// URL url = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<BookVolumeInfo> bookVolumeInfoList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
BookVolumeInfo bookVolumeInfo = new BookVolumeInfo();
BookAuthors bookAuthors = new BookAuthors();
BookCategories bookCategories = new BookCategories();
bookVolumeInfo.setTitle(finalObject.getString("title"));
bookVolumeInfo.setDescription(finalObject.getString("description"));
bookVolumeInfo.setAverageRating((float) finalObject.getDouble("averageRating"));
bookAuthors.setAuthors(finalObject.getString("authors"));
bookCategories.setCategories(finalObject.getString("categories"));
bookVolumeInfoList.add(bookVolumeInfo);
}
return bookVolumeInfoList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<BookVolumeInfo> result) {
super.onPostExecute(result);
textViewDisplayResult.setText((CharSequence) result);
}
}
}
When I am running the code it is not giving any errors but when I am searching for the book it says in the Android Monitor window, "title cannot be found".
Please help.
Generate Model Class from here
Here is the full implementation of your json body to a java class
public class DemoClass {
private Items[] items;
private String totalItems;
private String kind;
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getTotalItems ()
{
return totalItems;
}
public void setTotalItems (String totalItems)
{
this.totalItems = totalItems;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private VolumeInfo volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public VolumeInfo getVolumeInfo ()
{
return volumeInfo;
}
public void setVolumeInfo (VolumeInfo volumeInfo)
{
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class SearchInfo
{
private String textSnippet;
public String getTextSnippet ()
{
return textSnippet;
}
public void setTextSnippet (String textSnippet)
{
this.textSnippet = textSnippet;
}
}
public class AccessInfo
{
private String webReaderLink;
private String textToSpeechPermission;
private String publicDomain;
private String viewability;
private String accessViewStatus;
private Pdf pdf;
private Epub epub;
private String embeddable;
private String quoteSharingAllowed;
private String country;
public String getWebReaderLink ()
{
return webReaderLink;
}
public void setWebReaderLink (String webReaderLink)
{
this.webReaderLink = webReaderLink;
}
public String getTextToSpeechPermission ()
{
return textToSpeechPermission;
}
public void setTextToSpeechPermission (String textToSpeechPermission)
{
this.textToSpeechPermission = textToSpeechPermission;
}
public String getPublicDomain ()
{
return publicDomain;
}
public void setPublicDomain (String publicDomain)
{
this.publicDomain = publicDomain;
}
public String getViewability ()
{
return viewability;
}
public void setViewability (String viewability)
{
this.viewability = viewability;
}
public String getAccessViewStatus ()
{
return accessViewStatus;
}
public void setAccessViewStatus (String accessViewStatus)
{
this.accessViewStatus = accessViewStatus;
}
public Pdf getPdf ()
{
return pdf;
}
public void setPdf (Pdf pdf)
{
this.pdf = pdf;
}
public Epub getEpub ()
{
return epub;
}
public void setEpub (Epub epub)
{
this.epub = epub;
}
public String getEmbeddable ()
{
return embeddable;
}
public void setEmbeddable (String embeddable)
{
this.embeddable = embeddable;
}
public String getQuoteSharingAllowed ()
{
return quoteSharingAllowed;
}
public void setQuoteSharingAllowed (String quoteSharingAllowed)
{
this.quoteSharingAllowed = quoteSharingAllowed;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Pdf
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
public class Epub
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
}
public class SaleInfo
{
private RetailPrice retailPrice;
private String saleability;
private ListPrice listPrice;
private Offers[] offers;
private String buyLink;
private String isEbook;
private String country;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public String getSaleability ()
{
return saleability;
}
public void setSaleability (String saleability)
{
this.saleability = saleability;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public Offers[] getOffers ()
{
return offers;
}
public void setOffers (Offers[] offers)
{
this.offers = offers;
}
public String getBuyLink ()
{
return buyLink;
}
public void setBuyLink (String buyLink)
{
this.buyLink = buyLink;
}
public String getIsEbook ()
{
return isEbook;
}
public void setIsEbook (String isEbook)
{
this.isEbook = isEbook;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Offers
{
private RetailPrice retailPrice;
private ListPrice listPrice;
private String finskyOfferType;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public String getFinskyOfferType ()
{
return finskyOfferType;
}
public void setFinskyOfferType (String finskyOfferType)
{
this.finskyOfferType = finskyOfferType;
}
}
public class RetailPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
public class ListPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
}
public class VolumeInfo
{
private String pageCount;
private String averageRating;
private ReadingModes readingModes;
private String infoLink;
private String printType;
private String allowAnonLogging;
private String publisher;
private String[] authors;
private String canonicalVolumeLink;
private String title;
private String previewLink;
private String description;
private String ratingsCount;
private ImageLinks imageLinks;
private String contentVersion;
private String[] categories;
private String language;
private String publishedDate;
private IndustryIdentifiers[] industryIdentifiers;
private String maturityRating;
public String getPageCount ()
{
return pageCount;
}
public void setPageCount (String pageCount)
{
this.pageCount = pageCount;
}
public String getAverageRating ()
{
return averageRating;
}
public void setAverageRating (String averageRating)
{
this.averageRating = averageRating;
}
public ReadingModes getReadingModes ()
{
return readingModes;
}
public void setReadingModes (ReadingModes readingModes)
{
this.readingModes = readingModes;
}
public String getInfoLink ()
{
return infoLink;
}
public void setInfoLink (String infoLink)
{
this.infoLink = infoLink;
}
public String getPrintType ()
{
return printType;
}
public void setPrintType (String printType)
{
this.printType = printType;
}
public String getAllowAnonLogging ()
{
return allowAnonLogging;
}
public void setAllowAnonLogging (String allowAnonLogging)
{
this.allowAnonLogging = allowAnonLogging;
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public String[] getAuthors ()
{
return authors;
}
public void setAuthors (String[] authors)
{
this.authors = authors;
}
public String getCanonicalVolumeLink ()
{
return canonicalVolumeLink;
}
public void setCanonicalVolumeLink (String canonicalVolumeLink)
{
this.canonicalVolumeLink = canonicalVolumeLink;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getPreviewLink ()
{
return previewLink;
}
public void setPreviewLink (String previewLink)
{
this.previewLink = previewLink;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRatingsCount ()
{
return ratingsCount;
}
public void setRatingsCount (String ratingsCount)
{
this.ratingsCount = ratingsCount;
}
public ImageLinks getImageLinks ()
{
return imageLinks;
}
public void setImageLinks (ImageLinks imageLinks)
{
this.imageLinks = imageLinks;
}
public String getContentVersion ()
{
return contentVersion;
}
public void setContentVersion (String contentVersion)
{
this.contentVersion = contentVersion;
}
public String[] getCategories ()
{
return categories;
}
public void setCategories (String[] categories)
{
this.categories = categories;
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getPublishedDate ()
{
return publishedDate;
}
public void setPublishedDate (String publishedDate)
{
this.publishedDate = publishedDate;
}
public IndustryIdentifiers[] getIndustryIdentifiers ()
{
return industryIdentifiers;
}
public void setIndustryIdentifiers (IndustryIdentifiers[] industryIdentifiers)
{
this.industryIdentifiers = industryIdentifiers;
}
public String getMaturityRating ()
{
return maturityRating;
}
public void setMaturityRating (String maturityRating)
{
this.maturityRating = maturityRating;
}
public class ImageLinks
{
private String thumbnail;
private String smallThumbnail;
public String getThumbnail ()
{
return thumbnail;
}
public void setThumbnail (String thumbnail)
{
this.thumbnail = thumbnail;
}
public String getSmallThumbnail ()
{
return smallThumbnail;
}
public void setSmallThumbnail (String smallThumbnail)
{
this.smallThumbnail = smallThumbnail;
}
}
public class ReadingModes
{
private String text;
private String image;
public String getText ()
{
return text;
}
public void setText (String text)
{
this.text = text;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
public class IndustryIdentifiers
{
private String type;
private String identifier;
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getIdentifier ()
{
return identifier;
}
public void setIdentifier (String identifier)
{
this.identifier = identifier;
}
}
}
}
}
More over you can also use Gson(https://github.com/google/gson) to convert json string directly into java pojo objects like,
new Gson().fromJson(finalJson,GoogleBook.class);

JSON Parsing with GSON

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

Categories

Resources