After a lot of research I've been unable to find a resolution.
I have a JSP page backed by a servlet that I'm setting up to run on the Google App Engine. I've created a bean (Client) to facilitate the transfer of my form fields between the JSP and the servlet. This has been working fine in most cases.
As a part of my servlet, I do some validation on the user-entered form values. If there is validation error I use the RequestDispatcher to forward the request back to the JSP page so that an error message can be shown. When this happens, I get the following error:
org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to convert string "02-10-2011" to class "java.util.Date" for attribute "appointmentDate": Property Editor not registered with the PropertyEditorManager
Here are the segments of my code that may be of interest:
public class Client {
public Client() {}
private long clientId;
private String name;
private String address;
private String homePhone;
private String cellPhone;
private String workPhone;
private String fax;
private String city;
private String postalCode;
private String emailAddress;
private String directions;
private String style;
private String decoratingThemes;
private String comments;
private String referralSource;
private boolean emailList;
private Date appointmentDate;
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDirections() {
return directions;
}
public void setDirections(String directions) {
this.directions = directions;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getDecoratingThemes() {
return decoratingThemes;
}
public void setDecoratingThemes(String decoratingThemes) {
this.decoratingThemes = decoratingThemes;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getReferralSource() {
return referralSource;
}
public void setReferralSource(String referralSource) {
this.referralSource = referralSource;
}
public boolean isEmailList() {
return emailList;
}
public void setEmailList(boolean emailList) {
this.emailList = emailList;
}
public Date getAppointmentDate() {
return appointmentDate;
}
public void setAppointmentDate(Date appointmentDate) {
this.appointmentDate = appointmentDate;
}
}
The bean declaration on the page:
<jsp:useBean id="Client" class="com.HC.RaveDesigns.Entity.Client" scope="session"/>
The method forwarding the request.
private void dispatchError(String error, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
req.setAttribute("error",error);
RequestDispatcher rd = req.getRequestDispatcher("ManageClient.jsp");
rd.forward(req,resp);
}
This is because user sends you String not Date, and this is your job to convert this text into Date.
The fastest fix will be:
change the parameter type in setter type to String
convert string to Date inside this setter.
Example:
public void setAppointmentDate(String appointmentDate) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
this.appointmentDate = df.parse(appointmentDate);
}
Additionally, you should change getter in the same way or use fmt:formatDate like #duffymo has suggested. Also remember to handle date parse exception - Never trust user input
Use JSTL <fmt:formatDate> in your JSPs. You should be using JSTL.
You need to use DateFormat to parse that String into a java.util.Date:
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
formatter.setLenient(false);
Date d = formatter.parse("02-10-2011");
Related
I have a payload string and want to change it to values of entity. The payload as below:
{"resultCode":"200","resultMessage":"Success","consent":[{"name":"A","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"1.0","updateDate":1600658621871},{"name":"B","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"2.0","updateDate":1874819158457},{"name":"C","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"3.0","updateDate":1358819159457}]}
And the entities:
public class ListConsentResponse {
private String resultCode;
private String resultMessage;
private List<ConsentDTO> consent;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<ConsentDTO> getConsent() {
return consent;
}
public void setConsent(List<ConsentDTO> consent) {
this.consent = consent;
}
}
public class ConsentDTO {
private String name;
private String sourceSystem;
private String updateBy;
private String remark;
private String version;
private Timestamp updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceSystem() {
return sourceSystem;
}
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Timestamp getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
}
But when I parse to json using GsonBuilder :
ListConsentResponse listConsentResponse = Utility.createGsonObject()
.fromJson(payload, ListConsentResponse.class);
I have error:
com.google.gson.JsonSyntaxException: 1600658621871
Is there any way help me get parse the string with Timestamp value to entity. Or at least can I change the Timestamp value to String value in payload (For example change 1600658621871 to "1600658621871").
Thanks.
I am trying to get the value of a JSON response and display it in my textView and editText. But I get a null object reference as an error.
JSON Response:
{
"srNo": 1,
"date": "11/14/2019 12:00:00 AM",
"fieldEngineer": "Angel",
"accountName": "Forever 21 Megamall",
"irNo": 1,
"joNo": 1,
"address": "Mandaluyong City",
"contactPerson": "Jansen Babon",
"designation": "",
"contactNo": "",
"email": "",
"timeIn": "00:00:00",
"timeOut": "00:00:00",
"productType": "Security",
"problem": ""
}
Java class:
private void fetchData() {
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, retrofit2.Response<ResObj> response) {
ResObj resObj = response.body();
String srNo = resObj.getSrNo();
String date = resObj.getDate();
String fieldEngineer = resObj.getFieldEngineer();
String accountName = resObj.getAccountName();
String irNo = resObj.getIrNo();
String joNo = resObj.getJoNo();
String address = resObj.getAddress();
String contactPerson = resObj.getContactPerson();
String designation = resObj.getDesignation();
String contactNo = resObj.getContactNo();
String email = resObj.getEmail();
String timeIn = resObj.getTimeIn();
String timeOut = resObj.getTimeOut();
String productType = resObj.getProductType();
String problem = resObj.getProblem();
//the response I am getting here is null
tvSrNo.setText(srNo);
etdate.setText(date);
etfieldengineer.setText(fieldEngineer);
etaccname.setText(accountName);
etirno.setText(irNo);
etjono.setText(joNo);
JsonObject workObj = new JsonObject();
try {
workObj.addProperty("srNo", resObj.getSrNo());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
}
});
}
I tried using this tvSrNo.setText(resObj.getSrNo()) instead of tvSrNo.setText(srNo) but it still gets the same problem.
I am also using Retrofit.
I expect the result that JSON data will be placed in an editText or textView. But apparently, the response is getting null.
ResObj class:
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String message;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getSrNo() {
return srNo;
}
public void setSrNo(String srNo) {
this.srNo = srNo;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getJoNo() {
return joNo;
}
public void setJoNo(String joNo) {
this.joNo = joNo;
}
public String getIrNo() {
return irNo;
}
public void setIrNo(String irNo) {
this.irNo = irNo;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
at com.example.android.ras.MainActivity$3.onResponse(MainActivity.java:187)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Change your String to Integer
public class Codebeautify {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
// Getter Methods
public Integer getSrNo() {
return srNo;
}
public String getDate() {
return date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public Integer getIrNo() {
return irNo;
}
public Integer getJoNo() {
return joNo;
}
public String getAddress() {
return address;
}
public String getContactPerson() {
return contactPerson;
}
public String getDesignation() {
return designation;
}
public String getContactNo() {
return contactNo;
}
public String getEmail() {
return email;
}
public String getTimeIn() {
return timeIn;
}
public String getTimeOut() {
return timeOut;
}
public String getProductType() {
return productType;
}
public String getProblem() {
return problem;
}
// Setter Methods
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public void setDate(String date) {
this.date = date;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public void setAddress(String address) {
this.address = address;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public void setEmail(String email) {
this.email = email;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public void setProductType(String productType) {
this.productType = productType;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
Make your POJO class like this
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("srNo")
#Expose
private Integer srNo;
#SerializedName("date")
#Expose
private String date;
#SerializedName("fieldEngineer")
#Expose
private String fieldEngineer;
#SerializedName("accountName")
#Expose
private String accountName;
#SerializedName("irNo")
#Expose
private Integer irNo;
#SerializedName("joNo")
#Expose
private Integer joNo;
#SerializedName("address")
#Expose
private String address;
#SerializedName("contactPerson")
#Expose
private String contactPerson;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("contactNo")
#Expose
private String contactNo;
#SerializedName("email")
#Expose
private String email;
#SerializedName("timeIn")
#Expose
private String timeIn;
#SerializedName("timeOut")
#Expose
private String timeOut;
#SerializedName("productType")
#Expose
private String productType;
#SerializedName("problem")
#Expose
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
make sure to have Gson Converter in your retrofit instance
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
then make call and put the data in ArrayList
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
Note: NullPointerException because you did not declare SrNo inside the model class
Try to use a jason to java class generator:
http://www.jsonschema2pojo.org/
Source type: JSON
Annotation style: Gson( if you used GSON) or none
Include getters and setters
public class Example {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
first : Check response output,
you can Log.i or Toast it,,,
If your response not load or null ... - (the Problem in here)
Second : if respon Ok, Check your ResObj.getSrNo().
Print again... check
String srNo = resObj.getSrNo();
Log.i srNo... (problem or not)
Or checkyour Class Codebeautify
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject); // paramObject is empty object
You are passing empty JsonObject to your API parameter.
So you have to add parameter value to your paramObject. like this
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
// add other properties if you have
} catch (JSONException e) {
e.printStackTrace();
}
after that you should call your api like
Call<ResObj> call = userService.userLogin(paramObject);
As i am seeing the problem is in parsing, The retrofit can not mapping as your response is n't having ResObj as root.
{ "ResObj": { "srNo": 1, "date": "11/14/201912: 00: 00AM", "fieldEngineer": "Angel", "accountName": "Forever21Megamall", "irNo": 1, "joNo": 1, "address": "MandaluyongCity", "contactPerson": "JansenBabon", "designation": "", "contactNo": "", "email": "", "timeIn": "00: 00: 00", "timeOut": "00: 00: 00", "productType": "Security", "problem": "" } }
Modify your response or change your request
Call<JSONObject> call = userService.userLogin(paramObject);
Later in extract the values manually.
I am trying to get customers data in database based on condition where status of each customer is "Actve" this is the default value at the time of insertion but I am setting it deactivated in some query ultimately I want only those who have status "Active"
I did this
#Override
public List<Customer> listCustomers() {
return this.sessionFactory.getCurrentSession().createQuery("from customer).list();
}
But I am getting all active and deactivated customer
Then I did this
#Override
public List<Customer> listCustomers() {
return this.sessionFactory.getCurrentSession().createQuery("from com.mphasis.bharathbank.bean.customer where status="+"'Active'").list();
}
Here I am getting Exception
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/BharathBank] threw exception [Request processing failed; nested
exception is org.hibernate.QueryException: could not resolve property:
status of: com.mphasis.bharathbank.bean.Customer [from
com.mphasis.bharathbank.bean.Customer as c where c.status=Active]]
with root cause org.hibernate.QueryException: could not resolve
property: status of: com.mphasis.bharathbank.bean.Customer [from
com.mphasis.bharathbank.bean.Customer as c where c.status=Active]
Model Customer Class
#Entity(name="customer")
#Table(name="customer")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
#Column(name="CustID")
private int CustID;
#Column(name="Mobile_No")
private String mobileno;
#Column(name="F_Name")
private String fname;
#Column(name="L_Name")
private String lname;
#Column(name="Email_Id")
private String emailid;
#Column(name="DOB")
private String dob;
#Column(name="Gender")
private String gender;
#Column(name="Acc_No")
private String accno;
#Column(name="Pwd")
private String Pwd;
#Column(name="present_address")
private String present_address;
#Column(name="permanent_address")
private String permanent_address;
#Column(name="occupation")
private String occupation;
#Column(name="marital_status")
private String marital_status;
#Column(name="adhaar_card_no")
private String adhaar_no;
#Column(name="pan")
private String pan;
#Column(name="Balance")
private String initial_bal;
#Column(name="status")
private String accstatus;
public String getAccstatus() {
return accstatus;
}
public void setAccstatus(String accstatus) {
this.accstatus = accstatus;
}
public int getCustID() {
return CustID;
}
public void setCustID(int custID) {
CustID = custID;
}
public String getMobileno() {
return mobileno;
}
public void setMobileno(String mobileno) {
this.mobileno = mobileno;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAccno() {
return accno;
}
public void setAccno(String accno) {
this.accno = accno;
}
public String getPwd() {
return Pwd;
}
public void setPwd(String pwd) {
Pwd = pwd;
}
public String getPresent_address() {
return present_address;
}
public void setPresent_address(String present_address) {
this.present_address = present_address;
}
public String getPermanent_address() {
return permanent_address;
}
public void setPermanent_address(String permanent_address) {
this.permanent_address = permanent_address;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getMarital_status() {
return marital_status;
}
public void setMarital_status(String marital_status) {
this.marital_status = marital_status;
}
public String getAdhaar_no() {
return adhaar_no;
}
public void setAdhaar_no(String adhaar_no) {
this.adhaar_no = adhaar_no;
}
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getInitial_bal() {
return initial_bal;
}
public void setInitial_bal(String initial_bal) {
this.initial_bal = initial_bal;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
I have to map this JSONObject into a Java object.
This is my Json:
{"WALLET":{
"ID":"1234",
"BAL":"20.000",
"NAME":"Filomena",
"EMAIL":"filo#gmail.com",
"DOCS":[
{
"ID":"001",
"S":"0",
"TYPE":"CardId",
"VD":"2019"
}
],
"IBANS":[
{
"ID":"001",
"S":"1",
"DATA":"iban",
"SWIFT":"swiftCode",
"HOLDER":"holder"
}
],
"STATUS":"string",
"BLOCKED":"1",
"SDDMANDATES":[
{
"ID":"sddMandateId",
"S":"status",
"DATA":"iban",
"SWIFT":"swiftCode"
}
],
"LWID":"string",
"CARDS":[
{
"ID":"string",
"EXTRA":{
"IS3DS":"string",
"CTRY":"string",
"AUTH":"string",
"NUM":"string",
"EXP":"string",
"TYP":"string"
}
}
],
"FirstName":"string",
"LastName":"string",
"CompanyName":"string",
"CompanyDescription":"string",
"CompanyWebsite":"string"
}
}
This is my Java class:
public class Wallet {
private String id;
private String bal;
private String name;
private String email;
private List<Doc> docs;
private List<Iban> ibans;
private String status;
private String blocked;
private List<SddMandate> sddMandates ;
private String lwid;
private List<Card> cards;
private String firstName;
private String lastname;
private String companyName;
private String companyDescription;
private String companyWebSite;
public Wallet(){
}
public Wallet(String id, String bal, String name, String email, List<Doc> docs, List<Iban> ibans, String status,
String blocked, List<SddMandate> sddMandates, String lwid, List<Card> cards, String firstName,
String lastname, String companyName, String companyDescription, String companyWebSite) {
super();
this.id = id;
this.bal = bal;
this.name = name;
this.email = email;
this.docs = docs;
this.ibans = ibans;
this.status = status;
this.blocked = blocked;
this.sddMandates = sddMandates;
this.lwid = lwid;
this.cards = cards;
this.firstName = firstName;
this.lastname = lastname;
this.companyName = companyName;
this.companyDescription = companyDescription;
this.companyWebSite = companyWebSite;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBal() {
return bal;
}
public void setBal(String bal) {
this.bal = bal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public List<Iban> getIbans() {
return ibans;
}
public void setIbans(List<Iban> ibans) {
this.ibans = ibans;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBlocked() {
return blocked;
}
public void setBlocked(String blocked) {
this.blocked = blocked;
}
public List<SddMandate> getSddMandates() {
return sddMandates;
}
public void setSddMandates(List<SddMandate> sddMandates) {
this.sddMandates = sddMandates;
}
public String getLwid() {
return lwid;
}
public void setLwid(String lwid) {
this.lwid = lwid;
}
public List<Card> getCards() {
return cards;
}
public void setCards(List<Card> cards) {
this.cards = cards;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyDescription() {
return companyDescription;
}
public void setCompanyDescription(String companyDescription) {
this.companyDescription = companyDescription;
}
public String getCompanyWebSite() {
return companyWebSite;
}
public void setCompanyWebSite(String companyWebSite) {
this.companyWebSite = companyWebSite;
}
Now i'm trying to map the object with gson library.
Wallet walletDetails=gson.fromJson(rispostaGetWalletDetails.toString(), Wallet.class);
System.out.println("Balance: "+walletDetails.getBal());
Now when i try to call method on the object i have always null and not the real value.
How i can do?
You have a wrong root level.
Probably, you need to need to get one level down
JSONObject yourObject = json.get("WALLET");
Wallet walletDetails = gson.fromJson(yourObject.toString(), Wallet.class);
To have Gson handle the correct field name mapping while deserializing, you have to register a FieldNamingStrategy like this (using Java 8):
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(field -> field.getName().toUpperCase())
.create();
The strategy will convert each Java field name to match those in your JSON.
This will cover almost all your fields except for those upper-camel-cased in the JSON response, such as "LastName", "CompanyName", etc. In order to map those too, your FieldNamingStrategy will have to become a little bit smarter, like:
field -> {
String fname = field.getName();
return "firstName".equals(fname) || "companyName".equals(fname) /*etc...*/ ? capitalize(fname) : fname.toUpperCase();
}
and so on, I think you got the idea.
The capitalize() method you can find in libraries like Apache Commons Lang or write your own, it's just for examplification here.
Your object variable name doesn't match the json attribute name. "EMAIL" in json should have same EMAIL in object. To overcome this, you could mention #JsonProperty before your attribute declaraction.
for eg:
#JsonProperty("EMAIL")
private String email;
Below are the raw JSON string returned from Magento REST API call:
{
"1":{
"entity_id":"1",
"website_id":"1",
"email":"john.oliver#hbo.com",
"group_id":"1",
"created_at":"2015-04-21 12:47:00",
"disable_auto_group_change":"0",
"prefix":null,
"firstname":"John",
"middlename":null,
"lastname":"Oliver",
"suffix":null,
"taxvat":null,
"created_in":"Admin"
},
"2":{
"entity_id":"2",
"website_id":"1",
"email":"beck.johnson#yahoo.com",
"group_id":"1",
"created_at":"2015-04-21 13:40:48",
"disable_auto_group_change":"0",
"prefix":null,
"firstname":"Beckie",
"middlename":null,
"lastname":"Johnson",
"suffix":null,
"taxvat":null,
"created_in":"Admin"
}
}
I would like to construct the POJO for the first time and here are the classes:
public class Customers {
private Map<String, Customer> customerMap;
public Map<String, Customer> getCustomerMap() {
return customerMap;
}
public void setCustomerMap(Map<String, Customer> customerMap) {
this.customerMap = customerMap;
}
}
public class Customer {
private String entity_id;
private String website_id;
private String email;
private String group_id;
private String created_at;
private String disable_auto_group_change;
private String prefix;
private String firstname;
private String middlename;
private String lastname;
private String suffix;
private String taxvat;
private String created_in;
public String getEntity_id() {
return entity_id;
}
public void setEntity_id(String entity_id) {
this.entity_id = entity_id;
}
public String getWebsite_id() {
return website_id;
}
public void setWebsite_id(String website_id) {
this.website_id = website_id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getDisable_auto_group_change() {
return disable_auto_group_change;
}
public void setDisable_auto_group_change(String disable_auto_group_change) {
this.disable_auto_group_change = disable_auto_group_change;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTaxvat() {
return taxvat;
}
public void setTaxvat(String taxvat) {
this.taxvat = taxvat;
}
public String getCreated_in() {
return created_in;
}
public void setCreated_in(String created_in) {
this.created_in = created_in;
}
}
Then, I tried using Gson to do the parsing:
Gson gson = new Gson();
Customers customers = gson.fromJson(response.getBody(), Customers.class);
System.out.println(customers.getCustomerMap());
But the result is null.
I am suspecting the class format might be wrong, can anyone suggest what's the right format? The number 1 and 2 at the beginning of each set are automatically generated by Magento.
This doesn't work by default because Gson expects to have a field named "customerMap" in order to use the default deserialization. The easiest (NOT NECESSARILY BEST) solution would be to simply do this:
String jsonText = "{\"customerMap\":"+response.getBody()+"}";
Customers customers = gson.fromJson(jsonText, Customers.class);
By adding the field name around the outside of your mapping, Gson knows what to do, and the println will output, for instance:
{1=Customer#2f56a6be, 2=Customer#61dd1c39}
However, it would be better to write a custom deserializer for your Customers class, or to modify the output of Magneto to add the surrounding {"customerMap": and }
Do NOT try to do this:
Map<String, Customer> cust = gson.fromJson(jsonText, Map.class);
This will actually generate a Map of type Map<String, LinkedTreeMap>, where LinkedTreeMap is an internal gson class.