Elasticsearch improve search accuracy on Boolean query match, matchesNot, matchesPartial - java

Need a help about the implementation of how to improve the search accuracy of the elasticSearch logic on the JAVA side which is in the springboot application.
Why I am aiming for search accuracy? Because in the production side whenever I am searching for products using the search bar in the app ex. Laptops it shows different results of product also.
First I have a **controller class ** where the request goes to this endpoint:
#PostMapping("/bsl/view/products/sort-filter")
public Response<SearchByFilterByResponse> viewSortByFilterBy(#RequestBody SearchByDto searchBy) throws IOException{
return Response.success(elasticSearchProductBslService.viewSortByFilterBy(searchBy));
}
RequestBody contains the SearchByDto class where inside of that class I have the filterBy object, where inside of it the structure of query is there.
SearchByDto class:
SearchByDto class
FilterBy class:
private Map<String, List<String>> filter;
private List<KeyValue<String, String>> matches;
private List<KeyValue<String, String>> matchesPartial;
private List<KeyValue<String, String>> matchesNot;
private List<KeyValue<String, RangeValue>> ranges;
private List<String> discludeFieldNotNullAndEmpty;
public List<String> getDiscludeFieldNotNullAndEmpty() {
if(discludeFieldNotNullAndEmpty==null) {
this.discludeFieldNotNullAndEmpty = new ArrayList<>();
}
return discludeFieldNotNullAndEmpty;
}
public void setDiscludeFieldNotNullAndEmpty(List<String> discludeFieldNotNullAndEmpty) {
this.discludeFieldNotNullAndEmpty = discludeFieldNotNullAndEmpty;
}
public List<KeyValue<String, RangeValue>> getRanges() {
if(ranges==null) {
this.ranges = new ArrayList<>();
}
return ranges;
}
public void setRanges(List<KeyValue<String, RangeValue>> ranges) {
this.ranges = ranges;
}
public Map<String, List<String>> getFilter() {
if(filter==null) {
this.filter = new HashMap<>();
}
return filter;
}
public void setFilter(Map<String, List<String>> filter) {
this.filter = filter;
}
public List<KeyValue<String, String>> getMatches() {
if(matches==null) {
this.matches = new ArrayList<>();
}
return matches;
}
public void setMatches(List<KeyValue<String, String>> matches) {
this.matches = matches;
}
public List<KeyValue<String, String>> getMatchesPartial() {
if(matchesPartial==null) {
this.matchesPartial = new ArrayList<>();
}
return matchesPartial;
}
public void setMatchesPartial(List<KeyValue<String, String>> matchesPartial) {
this.matchesPartial = matchesPartial;
}
public List<KeyValue<String, String>> getMatchesNot() {
if(matchesNot==null) {
this.matchesNot = new ArrayList<>();
}
return matchesNot;
}
public void setMatchesNot(List<KeyValue<String, String>> matchesNot) {
this.matchesNot = matchesNot;
}
}
As based on the structure of the code the matches, matchesPartial, matchesNot is nested under the filter Map, and each keyword queries should have key and value.
Now let's go back to the controller class, as you can see inside of the Response.success method
it is calling also the elasticSearchProductBslService.viewSortByFilterBy(searchBy) where inside of the searchBy it contains the request including the filterBy.
Let's jump to the viewSortByFilterBy() method inside of the elasticSearchProductBslService class.
public SearchByFilterByResponse viewSortByFilterBy(SearchByDto searchBy) throws IOException{
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
SearchRequest request = new SearchRequest();
request.indices("product_bsl");
request.source(sourceBuilder);
int fromIndex = searchBy.getPagination().getFrom();
int size = searchBy.getPagination().getSize();
elasticSearchHelper.buildFieldSort(searchBy, sourceBuilder);
sourceBuilder.from(fromIndex);
sourceBuilder.size(size);
BoolQueryBuilder queryBuilder = elasticSearchHelper.boolQueryBuilder(searchBy);
sourceBuilder.query(queryBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits();
SearchByFilterByResponse resp = new SearchByFilterByResponse();
resp.setTotalHits(response.getHits().getTotalHits().value);
List<ProductWithImage> products = searchHitToDto(searchHits);
resp.setProducts(products);
return resp;
}
Additional information for you, this is the DTO class for "product_bsl" index. As I will show it to you how it look like in the OpenAPI later.
ProductBslElasticDto class:
public class ProductBslElasticDto {
private String id;
private String name;
private List<OfferElasticDto> offers;
private List<ProductBslElasticCategory> productBslElasticCategory;
private String brandId;
private String brandName;
private String shortdesc;
private String longDesc;
private int brandRating;
private long dateInserted;
private List<String> imagePath;
private String isActive;
private List<String> images;
private List<String> imageId;
private long totalVisits;
private long totalVisitUpdateTime;
private long totalViewCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getShortdesc() {
return shortdesc;
}
public void setShortdesc(String shortdesc) {
this.shortdesc = shortdesc;
}
public String getLongDesc() {
return longDesc;
}
public void setLongDesc(String longDesc) {
this.longDesc = longDesc;
}
public int getBrandRating() {
return brandRating;
}
public void setBrandRating(int brandRating) {
this.brandRating = brandRating;
}
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId = brandId;
}
public long getDateInserted() {
return dateInserted;
}
public void setDateInserted(long dateInserted) {
this.dateInserted = dateInserted;
}
public List<ProductBslElasticCategory> getProductBslElasticCategory() {
return productBslElasticCategory;
}
public void setProductBslElasticCategory(List<ProductBslElasticCategory> productBslElasticCategory) {
this.productBslElasticCategory = productBslElasticCategory;
}
public long getTotalVisits() {
return totalVisits;
}
public void setTotalVisits(long totalVisits) {
this.totalVisits = totalVisits;
}
public long getTotalVisitUpdateTime() {
return totalVisitUpdateTime;
}
public void setTotalVisitUpdateTime(long totalVisitUpdateTime) {
this.totalVisitUpdateTime = totalVisitUpdateTime;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public List<String> getImageId() {
return imageId;
}
public void setImageId(List<String> imageId) {
this.imageId = imageId;
}
public List<OfferElasticDto> getOffers() {
return offers;
}
public void setOffers(List<OfferElasticDto> offers) {
this.offers = offers;
}
public long getTotalViewCount() {
return totalViewCount;
}
public void setTotalViewCount(long totalViewCount) {
this.totalViewCount = totalViewCount;
}
public List<String> getImagePath() {
return imagePath;
}
public void setImagePath(List<String> imagePath) {
sortIndexedImagePaths(imagePath);
this.imagePath = imagePath;
}
private void sortIndexedImagePaths(List<String> imagePaths) {
if (null == imagePaths) return;
for (String path : imagePaths) {
if (null == path ||
!PRODUCT_INDEXED_IMAGE_PATH_PATTERN.matcher(path).find()) {
return;
}
}
imagePaths.sort(String::compareTo);
}
}
Now after I show the DTO you can look back to the viewSortByFilterBy() again. I think you can disregard the SourceBuilder and SearchRequest let's focus on the elasticSearchHelper.boolQueryBuilder(searchBy) as we will jump inside of it.
ElasticSearchHelper class:
#Service
public class ElasticSearchHelper {
private static final String KEY_NAME = "name";
private static final String REGEX_SPACE = " ";
private static final String REGEX_WILDCARD = "*";
public BoolQueryBuilder boolQueryBuilder(SearchByDto searchBy) {
FilterBy filterBy = searchBy.getFilterBy();
BoolQueryBuilder rootBuilder = QueryBuilders.boolQuery();
if(filterBy!=null) {
nestedTermsQueryBuilder(rootBuilder, filterBy.getFilter());
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatches(), MUST);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesNot(), MUST_NOT);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesPartial(), SHOULD);
nestedExistsQueryBuilder(rootBuilder, filterBy.getDiscludeFieldNotNullAndEmpty());
nestedRangeQueryBuilder(rootBuilder, filterBy.getRanges());
}
return rootBuilder;
}
private void nestedTermsQueryBuilder(BoolQueryBuilder rootBuilder, Map<String, List<String>> filter) {
filter.forEach((key, value) -> {
TermsQueryBuilder nestedBuilder = QueryBuilders.termsQuery(key, value);
rootBuilder.must(nestedBuilder);
});
}
private void nestedBoolQueryBuilder(BoolQueryBuilder rootBuilder, List<KeyValue<String, String>> entries, ElasticSearchBoolQueryType queryType) {
if(entries != null && !entries.isEmpty()) {
Set<String> distinctKeys = entries.stream().map(KeyValue::getKey).collect(Collectors.toSet());
for (String key : distinctKeys) {
BoolQueryBuilder nestedBuilder = QueryBuilders.boolQuery();
for (KeyValue<String, String> entry : entries) {
nestedQueryStringOrDisMaxQueryBuilder(key, entry, nestedBuilder);
}
switch (queryType) {
case MUST:
rootBuilder.must(nestedBuilder);
break;
case MUST_NOT:
rootBuilder.mustNot(nestedBuilder);
break;
case SHOULD:
rootBuilder.should(nestedBuilder);
break;
default:
break;
}
}
}
}
I just included the boolQueryBuilder and nestedBoolQueryBuilder only just to focus relating to my concern. don't get confuse on the MUST, MUST_NOT, SHOULD it is the same for matches, matchesNot, matchesPartial as I have told earlier on the FilterBy class. So in this class I think the logic happens here, any suggestions for any changes and how should I improve search accuracy for this kind of structure?
How it looks like in OpenAPI as I will search for product name:
Request: POST "/bsl/view/products/sort-filter"
{
"pagination": {
"from": 0,
"size": 20
},
"sortBy": {
"fieldsAscOrDesc": {
"offers.financing.finalAmount": "desc"
}
},
"filterBy": {
"matches": [
{
"key": "name",
"value": "Lenovo IdeaPad3 81Y4001NPH"
}
],
"matchesNot": [
{
"key": "isActive",
"value": "false"
}
],
"discludeFieldNotNullAndEmpty": [
"offers"
]
}
}
Result was it had total of 17 hits and I used the matches keyword where it should be search the exact word right? But it shows different Lenovo products in the result.
Result

Related

Retrieved data from JSON but can't Accessing Arraylist from JSONobject

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

how to convert string into Json and extrat from it info

I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.

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

Handle deep nested complex xml with FreeMarker

This is a part of a complex xml template which i put here for the question :
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgId>${MsgId}</MsgId>
<CreDtTm>${CreDtTm}</CreDtTm>
<NbOfTxs>${NbOfTxs}</NbOfTxs>
<a> ${val1}
<b>
${val2}
</b>
</a>
<CtrlSum>${CtrlSum}</CtrlSum>
</GrpHdr>
<PmtInf>
<PmtInfId>${PmtInfId}</PmtInfId>
<PmtMtd>${PmtMtd}</PmtMtd>
</PmtInf>
<#list persons as person>
</#list>
</CstmrDrctDbtInitn>
</Document>
I have been using FreeMarker for the previous month and until now the xml models have been easy
Searching over the web on how to approach this template , should i create matching java classes (100 of them ? )... should i use Map? like shown here .
I don't have a clue how to do it ... how to apply FreeMarker on this template ?
So here is a solution for any future users . Firstly i created 3 models which i am calling like below :
Map<String, Object> data = new HashMap<>();
//================= Example Creating HeaderVo //=================
HeaderVo header = new HeaderVo("la","la",5,5,"la","la");
data.put("header", header);
//================= Example Creating MiddleVo //=================
MiddleVo middleVo = new MiddleVo("la","la",5,"la","la","la","la");
data.put("middle", middleVo);
//================= Example Creating internal items =================
InternalVo v1 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","EUR");
InternalVo v2 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","DOLLARS");
InternalVo v3 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","LAT");
//List parsing
List<InternalVo> internalVos = new ArrayList<>();
internalVos.add(v1);
internalVos.add(v2);
internalVos.add(v3);
data.put("vos", internalVos);
//================= //================= //================= //=================
final String message = this.templateManager.composeStringFromTemplate(data, "bankfile.ftl");
So below is the bankfile.ftl which represents the complex xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02">
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgId>${header.msgId}</MsgId>
<CreDtTm>${header.creDtTm}</CreDtTm>
<NbOfTxs>${header.nbOfTxs}</NbOfTxs>
<CtrlSum>${header.ctrlSum}</CtrlSum>
<InitgPty>
<Nm>${header.nm}</Nm>
<Id>
<OrgId>
<Othr>
<Id>${header.id}</Id>
</Othr>
</OrgId>
</Id>
</InitgPty>
</GrpHdr>
<PmtInf>
<PmtTpInf>
<SvcLvl>
<Cd>${middle.svcLvlCD}</Cd>
</SvcLvl>
<LclInstrm>
<Cd>${middle.lclInstrmCD}</Cd>
</LclInstrm>
<SeqTp>${middle.seqTp}</SeqTp>
</PmtTpInf>
<ReqdColltnDt>${middle.reqdColltnDt}</ReqdColltnDt>
<Cdtr>
<Nm>${middle.nm}</Nm>
</Cdtr>
<CdtrAcct>
<Id>
<IBAN>${middle.iBAN}</IBAN>
</Id>
</CdtrAcct>
<CdtrAgt>
<FinInstnId>
<BIC>${middle.bIC}</BIC>
</FinInstnId>
</CdtrAgt>
<#list vos as vo>
<DrctDbtTxInf> <PmtId> <EndToEndId>${vo.endToEndId}</EndToEndId> </PmtId> <InstdAmt Ccy="${vo.ccy}">${vo.instdAmt}</InstdAmt> <DrctDbtTx> <MndtRltdInf> <MndtId>${vo.mndtId}</MndtId> <DtOfSgntr>${vo.dtOfSgntr}</DtOfSgntr> <AmdmntInd>${vo.amdmntInd?c}</AmdmntInd> </MndtRltdInf> </DrctDbtTx> <DbtrAgt> <FinInstnId> <BIC>${vo.bIC}</BIC> </FinInstnId> </DbtrAgt> <Dbtr> <Nm>${vo.nm}</Nm> </Dbtr> <DbtrAcct> <Id> <IBAN>${vo.iBAN}</IBAN> </Id> </DbtrAcct> </DrctDbtTxInf>
</#list>
</PmtInf>
</CstmrDrctDbtInitn>
</Document>
```
And finally here are the 3 models used for the FTL ( sorry for them being huge , i just wanted to so how complex it can get :) ):
HeaderVo
public class HeaderVo {
private String msgId;
private String creDtTm;
private int nbOfTxs;
private int ctrlSum;
private String nm;
private String id;
public HeaderVo() {
super();
}
public HeaderVo(String msgId, String creDtTm, int nbOfTxs, int ctrlSum, String nm, String id) {
super();
this.msgId = msgId;
this.creDtTm = creDtTm;
this.nbOfTxs = nbOfTxs;
this.ctrlSum = ctrlSum;
this.nm = nm;
this.id = id;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getCreDtTm() {
return creDtTm;
}
public void setCreDtTm(String creDtTm) {
this.creDtTm = creDtTm;
}
public int getNbOfTxs() {
return nbOfTxs;
}
public void setNbOfTxs(int nbOfTxs) {
this.nbOfTxs = nbOfTxs;
}
public int getCtrlSum() {
return ctrlSum;
}
public void setCtrlSum(int ctrlSum) {
this.ctrlSum = ctrlSum;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
MiddleVo
public class MiddleVo {
private String svcLvlCD;
private String lclInstrmCD;
private int seqTp;
private String reqdColltnDt;
private String nm;
private String iBAN;
private String bIC;
public MiddleVo() {
super();
}
public MiddleVo(String svcLvlCD, String lclInstrmCD, int seqTp, String reqdColltnDt, String nm, String iBAN,
String bIC) {
super();
this.svcLvlCD = svcLvlCD;
this.lclInstrmCD = lclInstrmCD;
this.seqTp = seqTp;
this.reqdColltnDt = reqdColltnDt;
this.nm = nm;
this.iBAN = iBAN;
this.bIC = bIC;
}
public String getSvcLvlCD() {
return svcLvlCD;
}
public void setSvcLvlCD(String svcLvlCD) {
this.svcLvlCD = svcLvlCD;
}
public String getLclInstrmCD() {
return lclInstrmCD;
}
public void setLclInstrmCD(String lclInstrmCD) {
this.lclInstrmCD = lclInstrmCD;
}
public int getSeqTp() {
return seqTp;
}
public void setSeqTp(int seqTp) {
this.seqTp = seqTp;
}
public String getReqdColltnDt() {
return reqdColltnDt;
}
public void setReqdColltnDt(String reqdColltnDt) {
this.reqdColltnDt = reqdColltnDt;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getiBAN() {
return iBAN;
}
public void setiBAN(String iBAN) {
this.iBAN = iBAN;
}
public String getbIC() {
return bIC;
}
public void setbIC(String bIC) {
this.bIC = bIC;
}
}
InternalVo
public class InternalVo {
private int endToEndId;
private int instdAmt;
private int mndtId;
private String dtOfSgntr;
private boolean amdmntInd;
private String bIC;
private String nm;
private String iBAN;
private String ccy;
public InternalVo() {
super();
}
public InternalVo(int endToEndId, int instdAmt, int mndtId, String dtOfSgntr, boolean amdmntInd, String bIC, String nm,
String iBAN,String ccy) {
super();
this.endToEndId = endToEndId;
this.instdAmt = instdAmt;
this.mndtId = mndtId;
this.dtOfSgntr = dtOfSgntr;
this.amdmntInd = amdmntInd;
this.bIC = bIC;
this.nm = nm;
this.iBAN = iBAN;
this.ccy = ccy;
}
public int getEndToEndId() {
return endToEndId;
}
public void setEndToEndId(int endToEndId) {
this.endToEndId = endToEndId;
}
public int getInstdAmt() {
return instdAmt;
}
public void setInstdAmt(int instdAmt) {
this.instdAmt = instdAmt;
}
public int getMndtId() {
return mndtId;
}
public void setMndtId(int mndtId) {
this.mndtId = mndtId;
}
public String getDtOfSgntr() {
return dtOfSgntr;
}
public void setDtOfSgntr(String dtOfSgntr) {
this.dtOfSgntr = dtOfSgntr;
}
public boolean isAmdmntInd() {
return amdmntInd;
}
public void setAmdmntInd(boolean amdmntInd) {
this.amdmntInd = amdmntInd;
}
public String getbIC() {
return bIC;
}
public void setbIC(String bIC) {
this.bIC = bIC;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getiBAN() {
return iBAN;
}
public void setiBAN(String iBAN) {
this.iBAN = iBAN;
}
public String getCcy() {
return ccy;
}
public void setCcy(String ccy) {
this.ccy = ccy;
}

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

Categories

Resources