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;
}
}
Related
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
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 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;
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.
I have a json string something similar
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","geo_position":{"latitude":52.39886,"longitude":13.06566}},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","geo_position":{"latitude":44.66978,"longitude":-74.98131}}]}
I am trying to convert to
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","latitude":52.39886,"longitude":13.06566},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","latitude":44.66978,"longitude":-74.98131}]}
I am converting to java and again converting back using But I am gettin null in data
SourceJSON data=new Gson().fromJson(jsonArray, SourceJSON.class);
DestinationJSON destdata = new DestinationJSON();
destdata.setLatitide(data.getGeoLocation().getLatitide());
destdata.setLongitude(data.getGeoLocation().getLongitude());
destdata.setId(data.getId());
destdata.setType(data.getType());
destdata.setName(data.getName());
destdata.set_type(data.get_type());
Gson gson = new Gson();
String json = gson.toJson(destdata);
below are my beans
public class SourceJSON implements Serializable {
private List<GEOLocation> geoLocations;
private String _type;
private String id;
private String name;
private String type;
public String get_type() {
return _type;
}
public List<GEOLocation> getGeoLocations() {
return geoLocations;
}
public void setGeoLocations(List<GEOLocation> geoLocations) {
this.geoLocations = geoLocations;
}
public void set_type(String _type) {
this._type = _type;
}
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
and
public class GEOLocation implements Serializable{
private String latitide;
private String longitude;
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
and destination java
public class DestinationJSON implements Serializable {
private String _type;
private String id;
private String name;
private String type;
private String latitide;
private String longitude;
public String get_type() {
return _type;
}
public void set_type(String _type) {
this._type = _type;
}
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
All you need is this. You can try this class in your IDE with a simple copy&paste.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20433539{
public static void main(String[] args){
String json = "{\"results\":"+
"[{\"_type\":\"Position\",\"_id\":377078,\"name\":\"Potsdam, Germany\",\"type\":\"location\",\"geo_position\":{\"latitude\":52.39886,\"longitude\":13.06566}},"+
"{\"_type\":\"Position\",\"_id\":410978,\"name\":\"Potsdam, USA\",\"type\":\"location\",\"geo_position\":{\"latitude\":44.66978,\"longitude\":-74.98131}}]}";
Gson gson = new Gson();
Map m = gson.fromJson(json, Map.class);
List<Map> innerList = (List<Map>) m.get("results");
for(Map result: innerList){
Map<String, Double> geo_position = (Map<String, Double>) result.get("geo_position");
result.put("latitude", geo_position.get("latitude"));
result.put("longitude", geo_position.get("longitude"));
result.remove("geo_position");
}
System.out.println(gson.toJson(m));
}
}
Of course, it works under the assumption that you always want to flat geo information.
Explanation: It's convenient to use POJO when working with Gson, but it's not the only way. Gson can also deseralize to Arrays/Maps if you do not specify the expected result. So I did, and then I manipulated the structure to unfold your data. After that, Gson can serialize Arrays/Maps structure again to your desidered JSON.