How to map string json to POJO class? - java

I have a body return this:
{
"a_name": "Max",
"a_surname": "Miles",
"a_details": {
"DETAILS": [
{
"DATE": "1996-12-31T00:00:00.000",
"AGE": "24",
"ACCNUM": "17",
"FORSPEC": "Smth written here",
"EXIT": "1"
}, ] //list of json
}
By now I am able to return name and surname, but having trouble mapping json field. Here is how my POJO looks like:
class Value {
String name;
String surname;
List<AccountDetail> detail;
//setter getter
}
class AccountDetail {
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
//setter getter
}
Here is a mapper for this field:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(
DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<AccountDetails> details = mapper.readValue(stringJson, Value.class);
But I am getting errors like unrecognized fields and so on. What is a problem? Maybe I should realize my POJO class in other way or I have a problem with mapper?

You can use Jackson library for Json reading, and use annotation for different name #JsonProperty("a_name")
Few more issues I found in your code:
This is incorrect - List<AccountDetail> detail
You should declare a field DETAILS, as a new class, and inside should be the list.
Also "EXIT" field is missing in the class you defined.
Full working example.
public String test() throws JsonProcessingException
{
String json = "your json here....";
ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultPrettyPrinter(new PrettyPrinter());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping();
mapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
mapper.readValue(json, Value.class);
return "success";
}
public static class PrettyPrinter extends DefaultPrettyPrinter
{
private static final long serialVersionUID = 1L;
public PrettyPrinter()
{
indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
}
}
private static class Value
{
#JsonProperty("a_name")
String name;
#JsonProperty("a_surname")
String surname;
#JsonProperty("a_details")
Details details;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public Details getDetails()
{
return details;
}
public void setDetails(Details details)
{
this.details = details;
}
}
private static class Details
{
#JsonProperty("DETAILS")
AccountDetail []detail;
public AccountDetail[] getDetail()
{
return detail;
}
public void setDetail(AccountDetail[] detail)
{
this.detail = detail;
}
}
private static class AccountDetail
{
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
public LocalDateTime getDATE()
{
return DATE;
}
public void setDATE(LocalDateTime DATE)
{
this.DATE = DATE;
}
public Number getAGE()
{
return AGE;
}
public void setAGE(Number AGE)
{
this.AGE = AGE;
}
public Number getACCNUM()
{
return ACCNUM;
}
public void setACCNUM(Number ACCNUM)
{
this.ACCNUM = ACCNUM;
}
public String getFORSPEC()
{
return FORSPEC;
}
public void setFORSPEC(String FORSPEC)
{
this.FORSPEC = FORSPEC;
}
public Number getEXIT()
{
return EXIT;
}
public void setEXIT(Number EXIT)
{
this.EXIT = EXIT;
}
}

You can used Gson library
public class JsonFormater {
public static void main(String[] args) {
Gson gs = new Gson();
// TODO Auto-generated method stub
String jsonstring = "{\n" + " \"a_name\":\"Max\",\n" + " \"a_surname\":\"Miles\",\n"
+ " \"a_details\":{\n" + " \"DETAILS\":[\n" + " {\n"
+ " \"DATE\":\"1996-12-31T00:00:00.000\",\n" + " \"AGE\":\"24\",\n"
+ " \"ACCNUM\":\"17\",\n" + " \"FORSPEC\":\"Smth written here\",\n"
+ " \"EXIT\":\"1\"\n" + " }\n" + " ]\n" + " }\n" + "}";
Information infomation = gs.fromJson(jsonstring, Information.class);
System.out.println(infomation.getaName());
System.out.println(infomation.getaSurname());
if (infomation.getaDetails() != null) {
TestData testdata = infomation.getaDetails();
for (Detail detail : testdata.getDetails()) {
System.out.println(detail.getAge());
}
}
}
}
public class Detail {
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("AGE")
#Expose
private String age;
#SerializedName("ACCNUM")
#Expose
private String accnum;
#SerializedName("FORSPEC")
#Expose
private String forspec;
#SerializedName("EXIT")
#Expose
private String exit;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAccnum() {
return accnum;
}
public void setAccnum(String accnum) {
this.accnum = accnum;
}
public String getForspec() {
return forspec;
}
public void setForspec(String forspec) {
this.forspec = forspec;
}
public String getExit() {
return exit;
}
public void setExit(String exit) {
this.exit = exit;
}
}
public class TestData {
#SerializedName("DETAILS")
#Expose
private List<Detail> details = null;
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
}
public class Information {
#SerializedName("a_name")
#Expose
private String aName;
#SerializedName("a_surname")
#Expose
private String aSurname;
#SerializedName("a_details")
#Expose
private TestData aDetails;
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaSurname() {
return aSurname;
}
public void setaSurname(String aSurname) {
this.aSurname = aSurname;
}
public TestData getaDetails() {
return aDetails;
}
public void setaDetails(TestData aDetails) {
this.aDetails = aDetails;
}
}
format your json correctly and try like this

Related

How to create Gson object for entity class which has timestamp value?

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.

How to display JSON data from API server in TextView and EditText in Android?

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.

Out of START_ARRAY token while reading a JSON in servlet

I have to create Java object from JSON string received in servlet
Below is the JSON
[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade#gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]
I tried to change the JSON that is by replacing [ by { and ] by } but it gives some other error.
My jackson code where I am getting exception is
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);
And the Enroll class is simple bean class with setter and getter
public class Enrole {
private String name;
private String email;
private long contactno;
private String address;
This is one of the way
try {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"name\",\"value\":\"Shital\"},{\"name\":\"email\",\"value\":\"swankhade#gmail.com\"},{\"name\":\"contactno\",\"value\":\"9920042776\"},{\"name\":\"Address\",\"value\":\"a6 102 Elementa\"}]";
KeyValue[] jsonObjArr = mapper.readValue(json, KeyValue[].class);
Enrole enrol = new Enrole();
for (int i = 0; i < jsonObjArr.length; i++) {
KeyValue keyVal = jsonObjArr[i];
if ("name".equals(keyVal.getName())) {
enrol.setName(keyVal.getValue());
}
if ("email".equals(keyVal.getName())) {
enrol.setEmail(keyVal.getValue());
}
if ("contactno".equals(keyVal.getName())) {
enrol.setContactno(Long.parseLong(keyVal.getValue()));
}
if ("address".equals(keyVal.getName())) {
enrol.setAddress(keyVal.getValue());
}
}
System.out.println(enrol.getName());
System.out.println(enrol.getContactno());
System.out.println(enrol.getAddress());
System.out.println(enrol.getEmail());
} catch (Exception e) {
System.out.println("Exception " + e);
}
Class with Key and Value :
class KeyValue {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Model Class
class Enrole {
private String name;
private String email;
private long contactno;
private String address;
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 long getContactno() {
return contactno;
}
public void setContactno(long contactno) {
this.contactno = contactno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

How to extract the methods of the a nested object using reflection

How do I access the getter methods of a nested custom object? I am able to extract the methods which return Strings but not able to extract methods of a nested object.
My implementation is as follows:
public class DataExtraction {
public void showTheData(Object student) throws IOException {
Class classofStudent = student.getClass();
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for(Method method:methodsOfStudent)
{
if(isGetType(method))
{
if(method.getReturnType()==String.class)
{
try(InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties"))
{
//InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(method.getName()));
}
}
else
try(InputStream is = new FileInputStream("ObjectFileReaderNonPrimitive.properties"))
{
Class innerObjectClass = method.getReturnType().getClass();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for(Method methodofInnerClass : methodsOfinnerObject) {
if(isGetType(method))
{
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(methodofInnerClass.getName()));
}
}}
}
}}
private boolean isGetType(Method method) {
if(method.getName().startsWith("get"))
return true;
return false;
}
}
Where the student class is as follows-:
package com.sample;
public class Student {
private String id;
private String section;
private Address address;
public Student(String id, String section, Address address) {
super();
this.id = id;
this.section = section;
this.address = address;
}
public Student() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Student [id=" + id + ", section=" + section + ", address=" + address + "]";
}
}
Address Object-:
package com.sample;
public class Address {
private String AddressLine1;
private String AddressLine2;
private String AddressLine3;
public Address(String addressLine1, String addressLine2, String addressLine3) {
super();
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
AddressLine3 = addressLine3;
}
public Address() {
super();
}
public String getAddressLine1() {
return AddressLine1;
}
public void setAddressLine1(String addressLine1) {
AddressLine1 = addressLine1;
}
public String getAddressLine2() {
return AddressLine2;
}
public void setAddressLine2(String addressLine2) {
AddressLine2 = addressLine2;
}
public String getAddressLine3() {
return AddressLine3;
}
public void setAddressLine3(String addressLine3) {
AddressLine3 = addressLine3;
}
#Override
public String toString() {
return "Address [AddressLine1=" + AddressLine1 + ", AddressLine2=" + AddressLine2 + ", AddressLine3="
+ AddressLine3 + "]";
}
}
Your problem is that you are not actually getting the correct class for your inner custom object.
Currently you are doing:
Class innerObjectClass = method.getReturnType().getClass();
This does not work because the method getReturnType is already returning the Class object of the return type. So what is happening is you are calling getClass() on a class object. This will return class java.lang.Class. You just need to remove the call to getClass:
Class innerObjectClass = method.getReturnType();
Here I have modified your code so that it prints all the getter objects in Student and Address
Class classofStudent = Student.class;
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for (Method method : methodsOfStudent) {
if (isGetType(method)) {
if (method.getReturnType() == String.class) {
System.out.println(method.getName());
} else {
Class innerObjectClass = method.getReturnType();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for (Method methodofInnerClass : methodsOfinnerObject) {
if (isGetType(method)) {
System.out.println(methodofInnerClass.getName());
}
}
}
}
}

Mapping JSON to Java Object return null value

I want to parsing json object like this:
{
"Count" : 1,
"Data" : [
{
"ContactID" : 1567993182,
"Email" : "enamdimensi#localhost.com",
"Action" : "unsub",
"Name" : "",
"Properties" : {}
}
],
"Total" : 1
}
to this java object.
public class Response {
#JsonProperty("Status")
private String status;
#JsonProperty("Data")
private List<DataResponse> data;
#JsonProperty("Total")
private Integer total;
#JsonProperty("Count")
private Integer count;
public MailjetResponse() {
super();
}
........ setter and getter .......
}
class DataResponse {
#JsonProperty("ContactID")
private String contactId;
#JsonProperty("Name")
private String name;
#JsonProperty("Email")
private String email;
#JsonProperty("Action")
private String action;
#JsonProperty("Properties")
private Map<String, Object> properties;
public DataResponse() {
super();
}
....... setter and getter .....
}
I used Jackson to do that, and this is my code:
final ObjectMapper mapper = new ObjectMapper();
MailjetResponse response = mapper.readValue(content, Response.class);
But, if I debug the response, all of the fields Response is null.
response [Status=null, Data=null, Total=null, Count=null]
is there something wrong with my code ?
UPDATED CODE:
Response class
public class Response {
#JsonProperty("Status")
private String status;
#JsonProperty("Data")
private List<DataResponse> data;
#JsonProperty("Total")
private Integer total;
#JsonProperty("Count")
private Integer count;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
#Override
public String toString() {
return "MailjetResponse [status=" + status + ", data=" + data
+ ", total=" + total + ", count=" + count + "]";
}
}
DataResponse class
public class DataResponse {
#JsonProperty("ContactID")
private String contactId;
#JsonProperty("Name")
private String name;
#JsonProperty("Email")
private String email;
#JsonProperty("Action")
private String action;
#JsonProperty("Properties")
private Map<String, Object> properties;
public String getContactID() {
return contactId;
}
public void setContactID(String contactID) {
contactId = contactID;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
email = email;
}
public String getAction() {
return action;
}
public void setAction(String action) {
action = action;
}
#Override
public String toString() {
return "DataResponse [contactId=" + contactId + ", name=" + name
+ ", email=" + email + ", action=" + action + ", properties="
+ properties + "]";
}
}
There result bocome like this:
response MailjetResponse [status=null, data=[DataResponse [contactId=1567993182, name=null, email=null, action=null, properties={}]], total=1, count=1]
I have tried your example and used setter only and got email field populated after deserialisation of json.I could not see any other issue.
Below is the code I have tried :
public class Response {
#JsonProperty("Status")
private String status;
#JsonProperty("Data")
private List<DataResponse> data;
#JsonProperty("Total")
private Integer total;
#JsonProperty("Count")
private Integer count;
public void setStatus(String status) {
this.status = status;
}
public void setData(List<DataResponse> data) {
this.data = data;
}
public void setTotal(Integer total) {
this.total = total;
}
public void setCount(Integer count) {
this.count = count;
}
}
public class DataResponse {
#JsonProperty("ContactID")
private String contactId;
#JsonProperty("Name")
private String name;
#JsonProperty("Email")
private String email;
#JsonProperty("Action")
private String action;
#JsonProperty("Properties")
private Map<String, Object> properties;
public void setContactId(String contactId) {
this.contactId = contactId;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setAction(String action) {
this.action = action;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
}
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
final Response response = mapper.readValue(message(), Response.class);
I will prefer to Jsoncreator annotated on constructor.
Problem
The problem is in your setters.
public void setEmail(String email) {
email = email;
}
This makes an unqualified assignment fron input arg email to ... input arg email (instead of the field this.email).
It should be:
public void setEmail(String email) {
this.email = email;
}
Jackson and annotated field access
Jackson uses setters unless configured otherwise. Either correct the setters (e.g. auto-generate them with IDE) or remove them and use fields only. To do that either annotate class with
#JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class DataResponse {
or change mapper settings, e.g.
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
Also: if you correct setters you may drop field annotations... Pick whatever is best for your use case. I prefer my jackson serialization to be done with just fields, always annotated - or with mixins.

Categories