success is false from server - java

Hi in the below code success is false from server while parsing json data.status code is 200 and created.
Login Modules class contains list of strings and GetModuleList contains a list of strings but in the modules is an array it contains a list of objects
LoginModules.java:
public class LoginModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<GetLoginModuleList> result;
public List<GetLoginModuleList> getResult() {
return result;
}
public void setResult(List<GetLoginModuleList> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
GetLoginModuleList.java:
public class GetLoginModuleList {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("modules")
#Expose
private List<Modules> modules;
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
}
GetLoginModulesList.java:
public class GetLoginModuleList {
#SerializedName("login")
private GetLoginList login;
public GetLoginList getLogin() {
return login;
}
public void setLogin(GetLoginList login) {
this.login = login;
}
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
#SerializedName("modules")
private List<Modules> modules;
}
Modules.java:
public class Modules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
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 getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
Json response:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
]
}
}
Activity.java:
if (response.isSuccessful()) {
LoginModules loginModules = response.body();
String success = loginModules.getSuccess()
.toString();
if (success.equals("true")) {
String result = loginModules.getResult()
.toString();
Log.i("result", ":" + result);
String Userid = loginModules.getResult()
.getUserid();
Log.i("Userid", ":" + Userid);
String Session = loginModules.getResult()
.getSession();
Log.i("Session", ":" + Session);
String Vtiger_version = loginModules.getResult()
.getVtiger_version();
Log.i("Vtiger_version", ":" + Vtiger_version);
String Mobile_module_version = loginModules.getResult()
.getMobile_module_version();
Log.i("Mobile_module_version", ":" + Mobile_module_version);
//List<Modules> modules = new ArrayList<>();
//Gson gson = new Gson();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray("modules");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = null;
try {
jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("id");
Log.i("id", ":" + id);
// String url = jsonobject.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (username.equals("admin") && pass.equals("Password!1")) {
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG)
.show();
}
}
}

Some data is missing in your model structure for parsing data.
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
there is a "login" jsonobject in your "result" object. But you missed the "login" element when you parse it. you should create a java class as LoginModel.
public class LoginModel {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
and put login model in your GetModuleList class.
public class GetLoginModuleList {
#SerializedName("login")
#Expose
private LoginModel login;

Related

Modules list is not coming after parsing json

Hi in the below code modules list is not coming after parsing the json and i have created different pojo classes for different classes and i am not getting the expected json response from server.
Can any one tell me where i did the mistake for json parsing and complete json is not coming as json
Activity.java:
final String username = username1.getText().toString();
final String password = password1.getText().toString();
String operation = "loginAndFetchModules";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<LoginAndFetchModules> call1 = service.GetLoginModuleList(operation, username, password);
/**Log the URL called*/
Log.wtf("URL Called", call1.request().url() + "");
call1.enqueue(new Callback<LoginAndFetchModules>() {
#Override
public void onResponse(Call<LoginAndFetchModules> call1, Response<LoginAndFetchModules> response) {
Log.e("response",new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response",new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
ArrayList<String> modules = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(loginAndFetchModules);
for (int i = 0; i < jsonArray.length(); i++) {
modules.add(jsonArray.get(i).toString());
JSONObject jsonObject=new JSONObject();
String id=jsonObject.getString("id").toString();
Log.i("id", ":" + id);
String name=jsonObject.getString("name").toString();
Log.i("name", ":" + name);
String isEntity=jsonObject.getString("isEntity").toString();
String label=jsonObject.getString("label").toString();
Log.i("isEntity", ":" + isEntity);
String singular=jsonObject.getString("singular").toString();
Log.i("singular", ":" + singular);
}//end for
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
LoginAndFetchModules.java:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<Results> result;
public List<Results> getResult() {
return result;
}
public void setResult(List<Results> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
Results.java:
public class Results {
#SerializedName("login")
#Expose
private GetLoginListDetails login;
#SerializedName("modules")
#Expose
private ArrayList<LoginListForModules> modules;
public ArrayList<LoginListForModules> getModules() {
return modules;
}
public void setModules(ArrayList<LoginListForModules> modules) {
this.modules = modules;
}
public GetLoginListDetails getLogin() {
return login;
}
public void setLogin(GetLoginListDetails login) {
this.login = login;
}
}
LoginListForModules.java:
public class LoginListForModules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
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 getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
GetLoginListDetails .java:
public class GetLoginListDetails {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
Expected output:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
{
"id": "3",
"name": "Accounts",
"isEntity": true,
"label": "Accounts",
"singular": "Account"
}]
}
}
According json response, it return Results instead of List. Change your LoginAndFetchModules like below:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private Results result;
public Results getResult() {
return result;
}
public void setResult(Results result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
And then parse the informations like below:
if (response.isSuccessful()) {
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for(LoginListForModules module: modules) {
String id = module.getId();
String name = module.getName();
...
}
}
}
you can create classes for response like this
first class is ResultReponse
public class ResultReponse implements Serializable {
#SerializedName("success")
private boolean success;
#SerializedName("result")
private ResultBean result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
}
ResultBean class
public class ResultBean implements Serializable{
#SerializedName("login")
private LoginBean login;
#SerializedName("modules")
private List<ModulesBean> modules;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
public List<ModulesBean> getModules() {
return modules;
}
public void setModules(List<ModulesBean> modules) {
this.modules = modules;
}
}
loginBean class inside ResultBean
public class LoginBean implements Serializable {
#SerializedName("userid")
private String userid;
#SerializedName("session")
private String session;
#SerializedName("vtiger_version")
private String vtiger_version;
#SerializedName("mobile_module_version")
private String mobile_module_version;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
ModulesBean class in list
public class ModulesBean implements Serializable {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("isEntity")
private boolean isEntity;
#SerializedName("label")
private String label;
#SerializedName("singular")
private String singular;
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 boolean isIsEntity() {
return isEntity;
}
public void setIsEntity(boolean isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
}

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

How to parse all json objects and send them inside a class?

This is the response JSON from Volley:
{
"status":true,
"data":{
"product_id":"12",
"product_ogpm_id":"OGPR1000485",
"product_part_number":"6ED1 057-1AA01-0BA0",
"escape_part_number":"6ed10571aa010ba0",
"product_name":"USB PC Cable",
"product_uom":"",
"product_image":"",
"product_description":"",
"product_manufacturer":"Siemens",
"manufacturer_id":"4",
"replace_id":"0",
"replace_date":"0000-00-00 00:00:00",
"product_added_date":"2017-09-12 00:57:15",
"product_added_by":"Jayank Chopra",
"product_modified_date":"0000-00-00 00:00:00",
"product_modified_by":"",
"product_status":"1",
"manufacturer_name":"Siemens",
"contracted_id":"1",
"data_sheets":[
]
},
"message":"Product found!"
}
For Parsing I use Gson Like this:
/* BarcodeSearchResponse responseObj = new Gson().fromJson(responseJson.toString(), BarcodeSearchResponse.class);
where BarcodeSearchResponse class is this:
public class BarcodeSearchResponse{
public ArrayList<ScanData> data;
}
*/
And ScanData is a class that contains :
public class ScanData implements Parcelable{
#SerializedName("product_id")
#Expose
private String productId;
#SerializedName("product_ogpm_id")
#Expose
private String productOgpmId;
#SerializedName("product_part_number")
#Expose
private String productPartNumber;
#SerializedName("escape_part_number")
#Expose
private String escapePartNumber;
#SerializedName("product_name")
#Expose
private String productName;
#SerializedName("product_uom")
#Expose
private String productUom;
#SerializedName("product_image")
#Expose
private String productImage;
#SerializedName("product_description")
#Expose
private String productDescription;
#SerializedName("product_manufacturer")
#Expose
private String productManufacturer;
#SerializedName("manufacturer_id")
#Expose
private String manufacturerId;
#SerializedName("replace_id")
#Expose
private String replaceId;
#SerializedName("replace_date")
#Expose
private String replaceDate;
#SerializedName("product_added_date")
#Expose
private String productAddedDate;
#SerializedName("product_added_by")
#Expose
private String productAddedBy;
#SerializedName("product_modified_date")
#Expose
private String productModifiedDate;
#SerializedName("product_modified_by")
#Expose
private String productModifiedBy;
#SerializedName("product_status")
#Expose
private String productStatus;
#SerializedName("manufacturer_name")
#Expose
private String manufacturerName;
#SerializedName("contracted_id")
#Expose
private String contractedId;
#SerializedName("data_sheets")
#Expose
private List<Object> dataSheets = null;
protected ScanData(Parcel in) {
productId = in.readString();
productOgpmId = in.readString();
productPartNumber = in.readString();
escapePartNumber = in.readString();
productName = in.readString();
productUom = in.readString();
productImage = in.readString();
productDescription = in.readString();
productManufacturer = in.readString();
manufacturerId = in.readString();
replaceId = in.readString();
replaceDate = in.readString();
productAddedDate = in.readString();
productAddedBy = in.readString();
productModifiedDate = in.readString();
productModifiedBy = in.readString();
productStatus = in.readString();
manufacturerName = in.readString();
contractedId = in.readString();
}
public static final Creator<ScanData> CREATOR = new Creator<ScanData>() {
#Override
public ScanData createFromParcel(Parcel in) {
return new ScanData(in);
}
#Override
public ScanData[] newArray(int size) {
return new ScanData[size];
}
};
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductOgpmId() {
return productOgpmId;
}
public void setProductOgpmId(String productOgpmId) {
this.productOgpmId = productOgpmId;
}
public String getProductPartNumber() {
return productPartNumber;
}
public void setProductPartNumber(String productPartNumber) {
this.productPartNumber = productPartNumber;
}
public String getEscapePartNumber() {
return escapePartNumber;
}
public void setEscapePartNumber(String escapePartNumber) {
this.escapePartNumber = escapePartNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductUom() {
return productUom;
}
public void setProductUom(String productUom) {
this.productUom = productUom;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public String getManufacturerId() {
return manufacturerId;
}
public void setManufacturerId(String manufacturerId) {
this.manufacturerId = manufacturerId;
}
public String getReplaceId() {
return replaceId;
}
public void setReplaceId(String replaceId) {
this.replaceId = replaceId;
}
public String getReplaceDate() {
return replaceDate;
}
public void setReplaceDate(String replaceDate) {
this.replaceDate = replaceDate;
}
public String getProductAddedDate() {
return productAddedDate;
}
public void setProductAddedDate(String productAddedDate) {
this.productAddedDate = productAddedDate;
}
public String getProductAddedBy() {
return productAddedBy;
}
public void setProductAddedBy(String productAddedBy) {
this.productAddedBy = productAddedBy;
}
public String getProductModifiedDate() {
return productModifiedDate;
}
public void setProductModifiedDate(String productModifiedDate) {
this.productModifiedDate = productModifiedDate;
}
public String getProductModifiedBy() {
return productModifiedBy;
}
public void setProductModifiedBy(String productModifiedBy) {
this.productModifiedBy = productModifiedBy;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
public String getContractedId() {
return contractedId;
}
public void setContractedId(String contractedId) {
this.contractedId = contractedId;
}
public List<Object> getDataSheets() {
return dataSheets;
}
public void setDataSheets(List<Object> dataSheets) {
this.dataSheets = dataSheets;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(productId);
parcel.writeString(productOgpmId);
parcel.writeString(productPartNumber);
parcel.writeString(escapePartNumber);
parcel.writeString(productName);
parcel.writeString(productUom);
parcel.writeString(productImage);
parcel.writeString(productDescription);
parcel.writeString(productManufacturer);
parcel.writeString(manufacturerId);
parcel.writeString(replaceId);
parcel.writeString(replaceDate);
parcel.writeString(productAddedDate);
parcel.writeString(productAddedBy);
parcel.writeString(productModifiedDate);
parcel.writeString(productModifiedBy);
parcel.writeString(productStatus);
parcel.writeString(manufacturerName);
parcel.writeString(contractedId);
}
}*/
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 24 path
$.data
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read
Please recheck your data. Maybe it look like bellow
{
"status": true,
"data": [
{
"product_id": "12",
"product_ogpm_id": "OGPR1000485",
"product_part_number": "6ED1 057-1AA01-0BA0",
"escape_part_number": "6ed10571aa010ba0",
"product_name": "USB PC Cable",
"product_uom": "",
"product_image": "",
"product_description": "",
"product_manufacturer": "Siemens",
"manufacturer_id": "4",
"replace_id": "0",
"replace_date": "0000-00-00 00:00:00",
"product_added_date": "2017-09-12 00:57:15",
"product_added_by": "Jayank Chopra",
"product_modified_date": "0000-00-00 00:00:00",
"product_modified_by": "",
"product_status": "1",
"manufacturer_name": "Siemens",
"contracted_id": "1",
"data_sheets": []
},
{
"product_id": "13",
"product_ogpm_id": "OGPR1000485",
"product_part_number": "6ED1 057-1AA01-0BA0",
"escape_part_number": "6ed10571aa010ba0",
"product_name": "USB PC Cable",
"product_uom": "",
"product_image": "",
"product_description": "",
"product_manufacturer": "Siemens",
"manufacturer_id": "4",
"replace_id": "0",
"replace_date": "0000-00-00 00:00:00",
"product_added_date": "2017-09-12 00:57:15",
"product_added_by": "Jayank Chopra",
"product_modified_date": "0000-00-00 00:00:00",
"product_modified_by": "",
"product_status": "1",
"manufacturer_name": "Siemens",
"contracted_id": "1",
"data_sheets": []
}
],
"message": "Product found!"
}
or if it same with you posted
Please make sure the BarcodeSearchResponse look like this:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BarcodeSearchResponse {
#SerializedName("status")
#Expose
private boolean status;
#SerializedName("data")
#Expose
private ScanData data;
#SerializedName("message")
#Expose
private String message;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ScanData getData() {
return data;
}
public void setData(ScanData data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Your POJO looks wrong. Your Data Class should look like this.
public class Data {
#SerializedName("product_id")
#Expose
private String productId;
#SerializedName("product_ogpm_id")
#Expose
private String productOgpmId;
#SerializedName("product_part_number")
#Expose
private String productPartNumber;
#SerializedName("escape_part_number")
#Expose
private String escapePartNumber;
#SerializedName("product_name")
#Expose
private String productName;
#SerializedName("product_uom")
#Expose
private String productUom;
#SerializedName("product_image")
#Expose
private String productImage;
#SerializedName("product_description")
#Expose
private String productDescription;
#SerializedName("product_manufacturer")
#Expose
private String productManufacturer;
#SerializedName("manufacturer_id")
#Expose
private String manufacturerId;
#SerializedName("replace_id")
#Expose
private String replaceId;
#SerializedName("replace_date")
#Expose
private String replaceDate;
#SerializedName("product_added_date")
#Expose
private String productAddedDate;
#SerializedName("product_added_by")
#Expose
private String productAddedBy;
#SerializedName("product_modified_date")
#Expose
private String productModifiedDate;
#SerializedName("product_modified_by")
#Expose
private String productModifiedBy;
#SerializedName("product_status")
#Expose
private String productStatus;
#SerializedName("manufacturer_name")
#Expose
private String manufacturerName;
#SerializedName("contracted_id")
#Expose
private String contractedId;
#SerializedName("data_sheets")
#Expose
private List<Object> dataSheets = null;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductOgpmId() {
return productOgpmId;
}
public void setProductOgpmId(String productOgpmId) {
this.productOgpmId = productOgpmId;
}
public String getProductPartNumber() {
return productPartNumber;
}
public void setProductPartNumber(String productPartNumber) {
this.productPartNumber = productPartNumber;
}
public String getEscapePartNumber() {
return escapePartNumber;
}
public void setEscapePartNumber(String escapePartNumber) {
this.escapePartNumber = escapePartNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductUom() {
return productUom;
}
public void setProductUom(String productUom) {
this.productUom = productUom;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public String getManufacturerId() {
return manufacturerId;
}
public void setManufacturerId(String manufacturerId) {
this.manufacturerId = manufacturerId;
}
public String getReplaceId() {
return replaceId;
}
public void setReplaceId(String replaceId) {
this.replaceId = replaceId;
}
public String getReplaceDate() {
return replaceDate;
}
public void setReplaceDate(String replaceDate) {
this.replaceDate = replaceDate;
}
public String getProductAddedDate() {
return productAddedDate;
}
public void setProductAddedDate(String productAddedDate) {
this.productAddedDate = productAddedDate;
}
public String getProductAddedBy() {
return productAddedBy;
}
public void setProductAddedBy(String productAddedBy) {
this.productAddedBy = productAddedBy;
}
public String getProductModifiedDate() {
return productModifiedDate;
}
public void setProductModifiedDate(String productModifiedDate) {
this.productModifiedDate = productModifiedDate;
}
public String getProductModifiedBy() {
return productModifiedBy;
}
public void setProductModifiedBy(String productModifiedBy) {
this.productModifiedBy = productModifiedBy;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
public String getContractedId() {
return contractedId;
}
public void setContractedId(String contractedId) {
this.contractedId = contractedId;
}
public List<Object> getDataSheets() {
return dataSheets;
}
public void setDataSheets(List<Object> dataSheets) {
this.dataSheets = dataSheets;
}
}
And your ScanData Class should use this Data Class as following.
public class ScanData {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
P.S.
I have not made it parcelable, I guess you can do that by yourself.

Map multi-level json string into class object in java

I have following JSON structure:
{
"result": {
"category": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}]
}]
},
{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}
]
}
}
I need to create class with the above JSON.
I have created two classes as HomeCategoryModel and HomeSubCategoryModel.
There may be multiple sub-categories in each level.
How to map this type of json into classes.
HomeCategoryModel class:
public class HomeCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//...
//getter, setter
}
HomeSubCategory class:
public class HomeSubCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//getter setter
}
I have tried to parse using recursive function like this but doesn't seem to work:
JSONObject allLists = jsonObject.getJSONObject("result");
JSONArray catArray = allLists.getJSONArray("category");
ArrayList<HomeCategoryModel> categoryList = new ArrayList<HomeCategoryModel>();
for (int i = 0; i < catArray.length(); i++) {
JSONObject jObj = catArray.getJSONObject(i);
HomeCategoryModel categoryModel = new HomeCategoryModel();
categoryModel.setId(Integer.parseInt(jObj.getString("id")));
categoryModel.setName(jObj.getString("name"));
categoryModel.setSlug(jObj.getString("slug"));
categoryModel.setImageUrl(jObj.getString("image"));
JSONArray productsArray = jObj.getJSONArray("sub-categories");
if (productsArray.length() > 0) {
parseSubCategories(productsArray);
}
categoryList.add(categoryModel);
}
And:
public static ArrayList<HomeSubCategoryModel> parseSubCategories(JSONArray arr) {
ArrayList<HomeSubCategoryModel> subLists = new ArrayList<HomeSubCategoryModel>();
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject childObj = arr.getJSONObject(i);
HomeSubCategoryModel categoryModel = new HomeSubCategoryModel();
categoryModel.setId(Integer.parseInt(childObj.getString("id")));
categoryModel.setName(childObj.getString("name"));
categoryModel.setSlug(childObj.getString("slug"));
categoryModel.setImageUrl(childObj.getString("image"));
JSONArray subArray = childObj.getJSONArray("sub-categories");
if (subArray.length() > 0) {
parseSubCategories(subArray);
}
subLists.add(categoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
return subLists;
}
Please suggest me. Thank you.
if you would like to use Gson then i can suggest something like below.
Generate your POJO like this
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public class Result {
#SerializedName("category")
#Expose
private List < Category > category = null;
public List < Category > getCategory() {
return category;
}
public void setCategory(List < Category > category) {
this.category = category;
}
}
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < SubCategory > subCategories = null;
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 getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < SubCategory > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < SubCategory > subCategories) {
this.subCategories = subCategories;
}
}
public class SubCategory_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < Object > subCategories = null;
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 getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < Object > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < Object > subCategories) {
this.subCategories = subCategories;
}
}
}
and then
Gson gson = new Gson();
Example exp = gson.fromJson("your json string",Example.class);
And you are done.

How to deserialize a JSON Object in a multidimensional array

I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}

Categories

Resources