how to convert string into Json and extrat from it info - java
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.
Related
How can I write Junit Test case which takes URI as input?
I am Trying to write test case for a method which takes URI as input and maps with modelmapper. however, I am getting null pointer exception for this. I have added every possible implementaion of class which I want to test. if you guy's need more for compilation tell me in comment section. this one is actual implementation which I want to mock #Override public ApplicationScanConfigDTO getApplicationScanConfig(int account_id, String appAppScanConfigId) { URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand") .queryParam("Account_Id", account_id).queryParam("applicationConfigScanId", appAppScanConfigId).build() .toUri(); return modelMapper.map(apiClient.getOperation(getUri, Object.class), ApplicationScanConfigDTO.class); } This is what I was trying #Test void testGetApplicationScanConfig() throws Exception { URI getUri = new URI("/api/scheduleOnDemand?Account_Id=1&applicationConfigScanId=1"); modelmapper.map(restTemplate.getForEntity(getUri, JSONObject.class), ApplicationScanConfigDTO.class); } apiclient implementation #Override public <R> R getOperation(URI uri, Class<R> rClasss) { URI builder = UriComponentsBuilder.fromHttpUrl(baseUrl) .path(uri.getPath()) .query(uri.getQuery()) .build() .toUri(); return restTemplate.getForObject(builder, rClasss); } ApplicationConfigDTO actual implementation: public class ApplicationScanConfigDTO { private Integer id; private String serverName; private Integer accountId; private String ipAddress; private String subnetRange; private Integer credentialId; private String credentialName; private String os; private List<String> ibmLibrary; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public Integer getAccountId() { return accountId; } public void setAccountId(Integer accountId) { this.accountId = accountId; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getSubnetRange() { return subnetRange; } public void setSubnetRange(String subnetRange) { this.subnetRange = subnetRange; } public Integer getCredentialId() { return credentialId; } public void setCredentialId(Integer credentialId) { this.credentialId = credentialId; } public String getCredentialName() { return credentialName; } public void setCredentialName(String credentialName) { this.credentialName = credentialName; } public String getOs() { return os; } public void setOs(String os) { this.os = os; } public List<String> getIbmLibrary() { return ibmLibrary; } public void setIbmLibrary(List<String> ibmLibrary) { this.ibmLibrary = ibmLibrary; } }
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()); } }); } }
Java Reflection to set each methods
I have a problem with setting up each field in my class by using the setter method. For my Object Class i have public class HealthDetails{ private String id; private String name; private String age; private String height; private String data0; private String data1; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; private String data10; private String data11; private String data12; private String data13; private String data14; private String data15; private String data16; private String data17; private String data18; private String data19; private String data20; private String data21; private String data22; private String data23; private String data24; private String data25; private String data26; private String data27; private String data28; private String data29; private String data30; private String data31; private String data32; private String data33; private String data34; private String data35; private String data36; private String data37; private String data38; private String data39; private String data40; private String data41; private String data42; private String data43; private String data44; private String data45; private String data46; private String data47; private String data48; private String data49; private String data50; private String data51; private String data52; private String data53; private String data54; private String data55; private String data56; private String data57; private String data58; private String data59; private String data60; private String data61; private String data62; private String data63; private String data64; private String data65; private String data66; private String data67; private String data68; private String data69; private String data70; private String data71; private String data72; private String data73; private String data74; private String data75; private String data76; private String data77; private String data78; private String data79; private String data80; private String data81; private String data82; private String data83; private String data84; private String data85; private String data86; private String data87; private String data88; private String data89; private String data90; private String data91; private String data92; private String data93; private String data94; private String data95; private String data96; private String data97; private String data98; private String data99; private String data100; private String data101; private String data102; private String data103; private String data104; private String data105; private String data106; private String data107; private String data108; private String data109; private String data110; private String data111; private String data112; private String data113; private String data114; private String data115; private String data116; private String data117; private String data118; private String data119; 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 getAge() { return age; } public void setAge(String age) { this.age = age; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getData0() { return data0; } public void setData0(String data0) { this.data0 = data0; } public String getData1() { return data1; } public void setData1(String data1) { this.data1 = data1; } public String getData2() { return data2; } public void setData2(String data2) { this.data2 = data2; } public String getData3() { return data3; } public void setData3(String data3) { this.data3 = data3; } public String getData4() { return data4; } public void setData4(String data4) { this.data4 = data4; } public String getData5() { return data5; } public void setData5(String data5) { this.data5 = data5; } public String getData6() { return data6; } public void setData6(String data6) { this.data6 = data6; } public String getData7() { return data7; } public void setData7(String data7) { this.data7 = data7; } public String getData8() { return data8; } public void setData8(String data8) { this.data8 = data8; } public String getData9() { return data9; } public void setData9(String data9) { this.data9 = data9; } public String getData10() { return data10; } public void setData10(String data10) { this.data10 = data10; } public String getData11() { return data11; } public void setData11(String data11) { this.data11 = data11; } public String getData12() { return data12; } public void setData12(String data12) { this.data12 = data12; } public String getData13() { return data13; } public void setData13(String data13) { this.data13 = data13; } public String getData14() { return data14; } public void setData14(String data14) { this.data14 = data14; } public String getData15() { return data15; } public void setData15(String data15) { this.data15 = data15; } public String getData16() { return data16; } public void setData16(String data16) { this.data16 = data16; } public String getData17() { return data17; } public void setData17(String data17) { this.data17 = data17; } public String getData18() { return data18; } public void setData18(String data18) { this.data18 = data18; } public String getData19() { return data19; } public void setData19(String data19) { this.data19 = data19; } public String getData20() { return data20; } public void setData20(String data20) { this.data20 = data20; } public String getData21() { return data21; } public void setData21(String data21) { this.data21 = data21; } public String getData22() { return data22; } public void setData22(String data22) { this.data22 = data22; } public String getData23() { return data23; } public void setData23(String data23) { this.data23 = data23; } public String getData24() { return data24; } public void setData24(String data24) { this.data24 = data24; } public String getData25() { return data25; } public void setData25(String data25) { this.data25 = data25; } public String getData26() { return data26; } public void setData26(String data26) { this.data26 = data26; } public String getData27() { return data27; } public void setData27(String data27) { this.data27 = data27; } public String getData28() { return data28; } public void setData28(String data28) { this.data28 = data28; } public String getData29() { return data29; } public void setData29(String data29) { this.data29 = data29; } public String getData30() { return data30; } public void setData30(String data30) { this.data30 = data30; } public String getData31() { return data31; } public void setData31(String data31) { this.data31 = data31; } public String getData32() { return data32; } public void setData32(String data32) { this.data32 = data32; } public String getData33() { return data33; } public void setData33(String data33) { this.data33 = data33; } public String getData34() { return data34; } public void setData34(String data34) { this.data34 = data34; } public String getData35() { return data35; } public void setData35(String data35) { this.data35 = data35; } public String getData36() { return data36; } public void setData36(String data36) { this.data36 = data36; } public String getData37() { return data37; } public void setData37(String data37) { this.data37 = data37; } public String getData38() { return data38; } public void setData38(String data38) { this.data38 = data38; } public String getData39() { return data39; } public void setData39(String data39) { this.data39 = data39; } public String getData40() { return data40; } public void setData40(String data40) { this.data40 = data40; } public String getData41() { return data41; } public void setData41(String data41) { this.data41 = data41; } public String getData42() { return data42; } public void setData42(String data42) { this.data42 = data42; } public String getData43() { return data43; } public void setData43(String data43) { this.data43 = data43; } public String getData44() { return data44; } public void setData44(String data44) { this.data44 = data44; } public String getData45() { return data45; } public void setData45(String data45) { this.data45 = data45; } public String getData46() { return data46; } public void setData46(String data46) { this.data46 = data46; } public String getData47() { return data47; } public void setData47(String data47) { this.data47 = data47; } public String getData48() { return data48; } public void setData48(String data48) { this.data48 = data48; } public String getData49() { return data49; } public void setData49(String data49) { this.data49 = data49; } public String getData50() { return data50; } public void setData50(String data50) { this.data50 = data50; } public String getData51() { return data51; } public void setData51(String data51) { this.data51 = data51; } public String getData52() { return data52; } public void setData52(String data52) { this.data52 = data52; } public String getData53() { return data53; } public void setData53(String data53) { this.data53 = data53; } public String getData54() { return data54; } public void setData54(String data54) { this.data54 = data54; } public String getData55() { return data55; } public void setData55(String data55) { this.data55 = data55; } public String getData56() { return data56; } public void setData56(String data56) { this.data56 = data56; } public String getData57() { return data57; } public void setData57(String data57) { this.data57 = data57; } public String getData58() { return data58; } public void setData58(String data58) { this.data58 = data58; } public String getData59() { return data59; } public void setData59(String data59) { this.data59 = data59; } public String getData60() { return data60; } public void setData60(String data60) { this.data60 = data60; } public String getData61() { return data61; } public void setData61(String data61) { this.data61 = data61; } public String getData62() { return data62; } public void setData62(String data62) { this.data62 = data62; } public String getData63() { return data63; } public void setData63(String data63) { this.data63 = data63; } public String getData64() { return data64; } public void setData64(String data64) { this.data64 = data64; } public String getData65() { return data65; } public void setData65(String data65) { this.data65 = data65; } public String getData66() { return data66; } public void setData66(String data66) { this.data66 = data66; } public String getData67() { return data67; } public void setData67(String data67) { this.data67 = data67; } public String getData68() { return data68; } public void setData68(String data68) { this.data68 = data68; } public String getData69() { return data69; } public void setData69(String data69) { this.data69 = data69; } public String getData70() { return data70; } public void setData70(String data70) { this.data70 = data70; } public String getData71() { return data71; } public void setData71(String data71) { this.data71 = data71; } public String getData72() { return data72; } public void setData72(String data72) { this.data72 = data72; } public String getData73() { return data73; } public void setData73(String data73) { this.data73 = data73; } public String getData74() { return data74; } public void setData74(String data74) { this.data74 = data74; } public String getData75() { return data75; } public void setData75(String data75) { this.data75 = data75; } public String getData76() { return data76; } public void setData76(String data76) { this.data76 = data76; } public String getData77() { return data77; } public void setData77(String data77) { this.data77 = data77; } public String getData78() { return data78; } public void setData78(String data78) { this.data78 = data78; } public String getData79() { return data79; } public void setData79(String data79) { this.data79 = data79; } public String getData80() { return data80; } public void setData80(String data80) { this.data80 = data80; } public String getData81() { return data81; } public void setData81(String data81) { this.data81 = data81; } public String getData82() { return data82; } public void setData82(String data82) { this.data82 = data82; } public String getData83() { return data83; } public void setData83(String data83) { this.data83 = data83; } public String getData84() { return data84; } public void setData84(String data84) { this.data84 = data84; } public String getData85() { return data85; } public void setData85(String data85) { this.data85 = data85; } public String getData86() { return data86; } public void setData86(String data86) { this.data86 = data86; } public String getData87() { return data87; } public void setData87(String data87) { this.data87 = data87; } public String getData88() { return data88; } public void setData88(String data88) { this.data88 = data88; } public String getData89() { return data89; } public void setData89(String data89) { this.data89 = data89; } public String getData90() { return data90; } public void setData90(String data90) { this.data90 = data90; } public String getData91() { return data91; } public void setData91(String data91) { this.data91 = data91; } public String getData92() { return data92; } public void setData92(String data92) { this.data92 = data92; } public String getData93() { return data93; } public void setData93(String data93) { this.data93 = data93; } public String getData94() { return data94; } public void setData94(String data94) { this.data94 = data94; } public String getData95() { return data95; } public void setData95(String data95) { this.data95 = data95; } public String getData96() { return data96; } public void setData96(String data96) { this.data96 = data96; } public String getData97() { return data97; } public void setData97(String data97) { this.data97 = data97; } public String getData98() { return data98; } public void setData98(String data98) { this.data98 = data98; } public String getData99() { return data99; } public void setData99(String data99) { this.data99 = data99; } public String getData100() { return data100; } public void setData100(String data100) { this.data100 = data100; } public String getData101() { return data101; } public void setData101(String data101) { this.data101 = data101; } public String getData102() { return data102; } public void setData102(String data102) { this.data102 = data102; } public String getData103() { return data103; } public void setData103(String data103) { this.data103 = data103; } public String getData104() { return data104; } public void setData104(String data104) { this.data104 = data104; } public String getData105() { return data105; } public void setData105(String data105) { this.data105 = data105; } public String getData106() { return data106; } public void setData106(String data106) { this.data106 = data106; } public String getData107() { return data107; } public void setData107(String data107) { this.data107 = data107; } public String getData108() { return data108; } public void setData108(String data108) { this.data108 = data108; } public String getData109() { return data109; } public void setData109(String data109) { this.data109 = data109; } public String getData110() { return data110; } public void setData110(String data110) { this.data110 = data110; } public String getData111() { return data111; } public void setData111(String data111) { this.data111 = data111; } public String getData112() { return data112; } public void setData112(String data112) { this.data112 = data112; } public String getData113() { return data113; } public void setData113(String data113) { this.data113 = data113; } public String getData114() { return data114; } public void setData114(String data114) { this.data114 = data114; } public String getData115() { return data115; } public void setData115(String data115) { this.data115 = data115; } public String getData116() { return data116; } public void setData116(String data116) { this.data116 = data116; } public String getData117() { return data117; } public void setData117(String data117) { this.data117 = data117; } public String getData118() { return data118; } public void setData118(String data118) { this.data118 = data118; } public String getData119() { return data119; } public void setData119(String data119) { this.data119 = data119; } } On the other hand I have a method call setListToPOJO public class Utility{ public static void setListToPOJO(List<String> objList, HealthDetails healthDetails){ Methods[] methods = healthDetails.getClass().getDeclaredMethods(); int i = 0; for(Method method : methods){ if(method.getName().startsWith("set"){ method.invoke(healthDetails, objList.get(i++)); } } //include all the try catch methods IllegalArgumentException / //IllegalArgumentException / InvocationTargetException } however i caught an argumentTypeMissmatch Any Idea how do i solve this without modifying the access Field? this is the method use to make it work the main class public class RunMethod{ public static void main(String[] args){ List<String> data = Arrays.asList("object0", "object1", "object2", "object3", "object4", "object5", "object6", "object7", "object8", "object9", "object10", "object11", "object12", "object13", "object14", "object15", "object16", "object17", "object18", "object19", "object20", "object21", "object22", "object23", "object24", "object25", "object26", "object27", "object28", "object29", "object30", "object31", "object32", "object33", "object34", "object35", "object36", "object37", "object38", "object39", "object40", "object41", "object42", "object43", "object44", "object45", "object46", "object47", "object48", "object49", "object50", "object51", "object52", "object53", "object54", "object55", "object56", "object57", "object58", "object59", "object60", "object61", "object62", "object63", "object64", "object65", "object66", "object67", "object68", "object69", "object70", "object71", "object72", "object73", "object74", "object75", "object76", "object77", "object78", "object79", "object80", "object81", "object82", "object83", "object84", "object85", "object86", "object87", "object88", "object89", "object90", "object91", "object92", "object93", "object94", "object95", "object96", "object97", "object98", "object99", "object100", "object101", "object102", "object103", "object104", "object105", "object106", "object107", "object108", "object109", "object110", "object111", "object112", "object113", "object114", "object115", "object116", "object117", "object118", "object119"); HealthDeatils healthDetails = new HealthDetails(); Utility.setListToPOJO(data,healthDetails); } } Below is the output Error Message (Edited): java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:592)
The cause is that the parameter you passed, objList.get(i++) is not the type the method you invoke required. modify you code to for(Method method : methods){ String value = objList.get(i); try { if(method.getName().startsWith("set"){ method.invoke(healthDetails, value); i++; } } catch (Exception e) { e.printStackTrace(); System.out.println("Value is: " + value); // show which value is wrong } } This would check which value type is wrong. On the other hand, for the wrong order of methods. I suggest you change objList from List<String> to Map<String, Obj>, the key is the name of the method you want to invoke, like Id, Name. Then you invoke it by just add set in front of it. for (Map.Entry<String, String> entry : map.entrySet()) { Object value = entry.getValue(); Method method = healthDetails.getClass().getDeclaredMethod("set"+entry.getKey(), value.getClass()); method.invoke(healthDetails, value); }
Your HealthDetails class have 124 properties and 124 setter methods but you are populating data list with only 120 elements causing ArrayIndexOutOfBoundsException while calling the setter methods through reflection. If we provide arguments for all the setter methods in that list your code will work without any issue. Below is the working modified code: public class RunMethod { public static void main(String[] args) { List<String> data = Arrays.asList("id", "name", "age", "height", " object0", "object1", "object2", "object3", "object4", "object5", "object6", "object7", "object8", "object9", "object10", "object11", "object12", "object13", "object14", "object15", "object16", "object17", "object18", "object19", "object20", "object21", "object22", "object23", "object24", "object25", "object26", "object27", "object28", "object29", "object30", "object31", "object32", "object33", "object34", "object35", "object36", "object37", "object38", "object39", "object40", "object41", "object42", "object43", "object44", "object45", "object46", "object47", "object48", "object49", "object50", "object51", "object52", "object53", "object54", "object55", "object56", "object57", "object58", "object59", "object60", "object61", "object62", "object63", "object64", "object65", "object66", "object67", "object68", "object69", "object70", "object71", "object72", "object73", "object74", "object75", "object76", "object77", "object78", "object79", "object80", "object81", "object82", "object83", "object84", "object85", "object86", "object87", "object88", "object89", "object90", "object91", "object92", "object93", "object94", "object95", "object96", "object97", "object98", "object99", "object100", "object101", "object102", "object103", "object104", "object105", "object106", "object107", "object108", "object109", "object110", "object111", "object112", "object113", "object114", "object115", "object116", "object117", "object118", "object119"); HealthDetails healthDetails = new HealthDetails(); Utility.setListToPOJO(data, healthDetails); } } Utility Class public class Utility{ public static void setListToPOJO(List objList, HealthDetails healthDetails) { System.out.println(objList.size()); Method[] methods = healthDetails.getClass().getDeclaredMethods(); System.out.println("methods array size " +methods.length); int i = 0; for (Method method : methods) { if (method.getName().startsWith("set")) { System.out.println(method.getName()); try { method.invoke(healthDetails, objList.get(i++)); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } }
A different approach. Currently, your code reads: Methods[] methods = healthDetails.getClass().getDeclaredMethods(); int i = 0; for(Method method : methods){ if(method.getName().startsWith("set"){ method.invoke(healthDetails, objList.get(i++)); } } The implicit assumption here is: the setter methods returned by getDeclaredMethods() are in the same order as your parameters (List<String> objList). First of all, that assumption is wrong. There is no guaranteed order in that array. But beyond that: when you know the order of elements in your list you simply don't need to use reflection at all. You just do: for (int i=0; i < objList.size(); i++) { String parm = objList.get(i); switch (i) { case 0: healthDetails.setId(parm); break; case 1: healthDetails.set...(parm); break; and so on. The point is, as stated multiple times: using a flat list means that you (somehow) must know in which order the arguments come in. And then you can simply use that order to determine the required setter method. In other words: the code example you are showing implies that you do not need to use reflection to solve this problem. At all. Your idea to use reflection only buys you complexity, nothing else. ( of course: when the input would be a Map<String, String> that provided the field names, things would be different. but as long as you use a list with a fixed order, there is no need and point using reflection! ) Given the update, the only real answer there is: don't use 100+ fields named data1, data2, ... that is what arrays/list are for.
how to change method name dynamically in loop in java
I have a bean class and i want to fetch MediaContentType0, MediaContentType1, MediaContentType2, MediaContentType3 in a loop i have get json string and convert it into java class using gson Gson gson=new Gson(); CommonBean commonBean=gson.fromJson("JsonString",CommonBean.class) for(int i=0;i<numberOfMedia;i++) { commonBean.getMediaUrl0(); commonBean.getMediaUrl1(); commonBean.getMediaUrl2(); //but i want it to fetch dynamically by iTh element. like- commonBean.getMediaUrl+i+(); How Could this possibe? Please Suggest. Thanks } mybean class is following :- public class CommonBean { public String to; public String from; public String body; public String numMedia; public String MediaContentType0 ; public String MediaContentType1 ; public String MediaContentType2 ; public String MediaContentType3; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getNumMedia() { return numMedia; } public void setNumMedia(String numMedia) { this.numMedia = numMedia; } public String getMediaContentType0() { return MediaContentType0; } public void setMediaContentType0(String mediaContentType0) { MediaContentType0 = mediaContentType0; } public String getMediaContentType1() { return MediaContentType1; } public void setMediaContentType1(String mediaContentType1) { MediaContentType1 = mediaContentType1; } public String getMediaContentType2() { return MediaContentType2; } public void setMediaContentType2(String mediaContentType2) { MediaContentType2 = mediaContentType2; } public String getMediaContentType3() { return MediaContentType3; } public void setMediaContentType3(String mediaContentType3) { MediaContentType3 = mediaContentType3; } } Please suggest how to fetch these element dynamically using getter method?
You can use the Java Reflection API for(int i=0;i<numberOfMedia;i++) { try { Method getterMethod = commonBean.getClass().getMethod("getMediaUrl"+i); getterMethod.invoke(commonBean); } catch(Exception e) {} }
how to write junit test cases for Row Mapper class in spring
Hi This is my Row Mapper class. public class UserRowMapper implements RowMapper<UserData> { #Override public UserData mapRow(ResultSet resultSet, int line) throws SQLException { UserData userData = new UserData(); try { userData.setUserID(resultSet.getString("User_ID")); userData.setUserName(resultSet.getString("User_Name")); userData.setUserPassword(resultSet.getString("User_Password")); userData.setUserRole(resultSet.getString("User_Role")); userData.setUserStatus(resultSet.getString("User_Status")); userData.setUserLogStatus(resultSet.getString("UserLog_Status")); userData.setUserAccountName(resultSet.getString("User_AccountName")); userData.setUserAccountID(resultSet.getString("User_AccountID")); userData.setUserEmailID(resultSet.getString("User_EmailID")); userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus")); userData.setUserIDStatus(resultSet.getString("User_ID_Status")); userData.setAcatTenantID(resultSet.getLong("acatTenant_ID")); userData.setUserRoleCode(resultSet.getLong("User_Role_Code")); userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code")); userData.setUserAccountCode(resultSet.getLong("User_Account_Code")); return userData; } catch (EmptyResultDataAccessException e) { return null; } } } and this is my Model class. public class UserData { private String userID; private String userPassword; private String userRole; private String userStatus; private String userLogStatus; private String userName; private String userAccountName; private String userAccountID; private String userIDStatus; private String userPasswordStatus; private String userEmailID; private String userAdminID; private String deactivationComment; private String reqPageID; private String userSessionID; private String reqFunctionalityID; private long userAccountCode; private long userRoleCode; private long userSkillSetCode; private long acatTenantID; public long getUserAccountCode() { return userAccountCode; } public void setUserAccountCode(long userAccountCode) { this.userAccountCode = userAccountCode; } public long getUserRoleCode() { return userRoleCode; } public void setUserRoleCode(long userRoleCode) { this.userRoleCode = userRoleCode; } public long getUserSkillSetCode() { return userSkillSetCode; } public void setUserSkillSetCode(long userSkillSetCode) { this.userSkillSetCode = userSkillSetCode; } public long getAcatTenantID() { return acatTenantID; } public void setAcatTenantID(long acatTenantID) { this.acatTenantID = acatTenantID; } public String getReqFunctionalityID() { return reqFunctionalityID; } public void setReqFunctionalityID(String reqFunctionalityID) { this.reqFunctionalityID = reqFunctionalityID; } public String getReqPageID() { return reqPageID; } public void setReqPageID(String reqPageID) { this.reqPageID = reqPageID; } public String getUserSessionID() { return userSessionID; } public void setUserSessionID(String userSessionID) { this.userSessionID = userSessionID; } public String getUserAdminID() { return userAdminID; } public void setUserAdminID(String userAdminID) { this.userAdminID = userAdminID; } public String getDeactivationComment() { return deactivationComment; } public void setDeactivationComment(String deactivationComment) { this.deactivationComment = deactivationComment; } public String getUserIDStatus() { return userIDStatus; } public void setUserIDStatus(String userIDStatus) { this.userIDStatus = userIDStatus; } public String getUserPasswordStatus() { return userPasswordStatus; } public void setUserPasswordStatus(String userPasswordStatus) { this.userPasswordStatus = userPasswordStatus; } public String getUserEmailID() { return userEmailID; } public void setUserEmailID(String userEmailID) { this.userEmailID = userEmailID; } public String getUserAccountID() { return userAccountID; } public void setUserAccountID(String userAccountID) { this.userAccountID = userAccountID; } public String getUserAccountName() { return userAccountName; } public void setUserAccountName(String userAccountName) { this.userAccountName = userAccountName; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserRole() { return userRole; } public void setUserRole(String userRole) { this.userRole = userRole; } public String getUserStatus() { return userStatus; } public void setUserStatus(String userStatus) { this.userStatus = userStatus; } public String getUserLogStatus() { return userLogStatus; } public void setUserLogStatus(String userLogStatus) { this.userLogStatus = userLogStatus; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes. Hi here is my Junit test code for above classes. public class UserRowMapperTest { UserRowMapper userRowMapper=null; #Before public void runBeforeEachTest(){ userRowMapper= new UserRowMapper(); } #After public void runAfterEachTest(){ userRowMapper=null; } #Test public void testMapRow(){ userRowMapper.mapRow(resultSet, line); } }
From my point of view there is nothing to test here. You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything. However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve. In general this is the sketch of what you want: #Test public void testMapRow(){ // SETUP SUT UserRowMapper userRowMapper = new UserRowMapper() // fill (prepare) in the Object that you want to pass to a method. ResultSet resultSet = createResultSet(); // EXERCISE UserData resultData = userRowMapper.mapRow(resultSet, line); // VERIFY Assert.assertEquals(expectedValue, resultData.getSomeValue()) } p.s. By the way, there is no point in line parameter in this method because you don't use it. And about the NullPointerException, please, have a look to quite popular question about it.