How to map JSONObject in Java object - java

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;

Related

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

Java Arraylist change one attribute value in all objects at the same time

I have a model with this attribute
public class Audit extends BaseModel implements Comparable {
#Column
#PrimaryKey
#SerializedName("audit_id")
private int id;
#Column
#SerializedName("address_line_1")
private String addressLine1;
#Column
#SerializedName("address_line_2")
private String addressLine2;
#Column
#SerializedName("city_name")
private String city;
#Column
#SerializedName("zip_code")
private String zipcode;
#Column
#SerializedName("company_id")
private int companyId;
#Column
#SerializedName("company_name")
private String companyName;
#Column
#SerializedName("loc_name")
private String location;
#Column
#SerializedName("inspection_date_time")
private OffsetDateTime inspectionTime;
#Column
#SerializedName("inspection_number")
private String inspectionNumber;
#Column(defaultValue = "0")
private int auditStatus;
#Column(defaultValue = "0")
private int userId;
public int getId() {
return id;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCity() {
return city;
}
public String getZipcode() {
return zipcode;
}
public int getCompanyId() {
return companyId;
}
public String getCompanyName() {
return companyName;
}
public String getLocation() {
return location;
}
public OffsetDateTime getInspectionTime() {
return inspectionTime;
}
public String getInspectionNumber() {
return inspectionNumber;
}
public void setId(int id) {
this.id = id;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCity(String city) {
this.city = city;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setLocation(String location) {
this.location = location;
}
public void setInspectionTime(OffsetDateTime inspectionTime) {
this.inspectionTime = inspectionTime;
}
public void setInspectionNumber(String inspectionNumber) {
this.inspectionNumber = inspectionNumber;
}
#Override
public int compareTo(#NonNull Object audits) {
int result = -1;
if (audits instanceof Audit) {
Audit audit = (Audit) audits;
if (this.getInspectionTime().isEqual(audit.getInspectionTime())) {
result = 0;
} else if
(this.getInspectionTime().isAfter(audit.getInspectionTime())) {
result = 1;
}
}
return result;
}
public int getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(int auditStatus) {
this.auditStatus = auditStatus;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
In here I get all values to Arraylist using this model
List<Audit> auditList
My list is "auditList", It contains Audit objects, In this auditList I want to chnge one attribute
for ex: I want to change userId value to "3" in all objects, How can I do it once, Is there any solution please Help Me
Using Java 8 Stream :
auditList.stream().forEach(elt -> elt.setUserId(3));
It corresponds to :
for (Audit aud : auditList) {
aud.setUserId(3);
}
You will need to iterate through all elements and update
for (Audit aud : auditList) {
aud.setUserId(3);
}
If you want it on one line then
for (Audit aud : auditList) aud.setUserId(3);

override equals of a custom object (called by contains method of a list)

I have two types of user, LibraUsers and GenesysUser. Each have their own properties, but some are similar.
I need to find the differences between two lists of these types of users. Made a small program to illustrate my problem - My issue is that I have duplicate entries in my difference list, the compare method on the list does not seem to do its job. I've read that I should override the equals method, and also the hashcode (in this case of the LibraUser). I tried that using an apache function, but it did not work.
The question therefore is, what are the alternatives for solving this problem?
import java.util.ArrayList;
import java.util.List;
// one class needs to have a main() method
public class HelloWorld {
public static List<LibraUser> libraUsers = new ArrayList<LibraUser>();
public static List<GenesysUser> genesysUsers = new ArrayList<GenesysUser>();
public static List<LibraUser> difference = new ArrayList<LibraUser>();
public static void initialiseGenesysUsers() {
// GenesysUser(String alias, String firstname, String lastname, String email)
genesysUsers.add(new GenesysUser("Donna", "Donna", "Paulsen", "donna#gmail.com", true));
genesysUsers.add(new GenesysUser("TheHarv", "Harvey", "Specter", "harvey#gmail.com", true));
genesysUsers.add(new GenesysUser("Rache", "Rachel", "Zane", "rachel#gmail.com", true));
genesysUsers.add(new GenesysUser("Mike", "Mike", "Ross", "mike#gmail.com", true));
}
public static void initialiseLibraUsers() {
// LibraUser(String name, String email, String telephone) {
libraUsers.add(new LibraUser("Louis", "louis#gmail.com", "0447521082"));
libraUsers.add(new LibraUser("Jessica", "jessica#gmail.com", "0447521044"));
libraUsers.add(new LibraUser("Mike", "mike#gmail.com", ""));
}
public static void getDifference() {
for (LibraUser librauser : libraUsers) {
for (GenesysUser genesysuser : genesysUsers) {
String genusername = genesysuser.getFirstname();
LibraUser dummy = new LibraUser(genusername, genesysuser.getEmail(), "");
if (!difference.contains(dummy)) {
// do the actual comparison using the relevant keys and insert into a new list
if (!librauser.getUsername().equals(genusername)) {
difference.add(dummy);
}
}
} // inner for loop
}// outer for loop
}
public static void printDifference() {
for (LibraUser usr : difference) {
System.out.println(usr.getUsername());
}
}
// arguments are passed using the text field below this editor
public static void main(String[] args) {
initialiseGenesysUsers();
initialiseLibraUsers();
getDifference();
printDifference();
}
}
public class GenesysUser {
private String Alias;
private String Firstname;
private String Lastname;
private String Email;
private boolean Active;
public GenesysUser(String alias, String firstname, String lastname, String email, boolean active) {
Alias = alias;
Firstname = firstname;
Lastname = lastname;
Email = email;
Active = active;
}
public String getAlias() {
return Alias;
}
public String getFirstname() {
return Firstname;
}
public String getLastname() {
return Lastname;
}
public String getEmail() {
return Email;
}
public void setAlias(String alias) {
Alias = alias;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public void setEmail(String email) {
Email = email;
}
public void setActive(boolean active) {
Active = active;
}
public boolean getActive() {
return Active;
}
}
public class LibraUser {
private String username;
private String email;
private String telephone;
public LibraUser(String username, String email, String telephone) {
this.username = username;
this.email = email;
this.telephone = telephone;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public String getTelephone() {
return this.telephone;
}
public void setName(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof LibraUser)) {
return false;
}
LibraUser user = (LibraUser) o;
return new EqualsBuilder()
.append(username, user.getUsername())
.append(email, user.getEmail())
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(username)
.append(email)
.toHashCode();
}
}
You need to use .equals instead of == to test the equality
if(librauser.getUsername() != genusername)
should be replaced with
if(!librauser.getUsername().equqls(genusername))

Designing Java Objects from Magento JSON

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.

while getting values in the form it returns null value

while getting values in the form the bindFromRequest().get() it returns only null value.I got all the String type is null and integr as zer0. Here is my code for controller and model packages and how I can resolve this error:
enter code here
In controller:
public static Result getShow(){
Register register=Form.form(Register.class).bindFromRequest().get();
register.save();
System.out.println(register);
return ok("#Required annotation kicked in.."+register);
}
In Models:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="register")
public class Register {
//private static final long serialVersionUID = 1L;
private String firstname;
private String lastname;
#Id
private String displayname;
private String date;
private String email;
private String password;
private String confirm_password;
private String gender;
private int phone_no;
private String address;
private int zipcode;
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 getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirm_password() {
return confirm_password;
}
public void setConfirm_password(String confirm_password) {
this.confirm_password = confirm_password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone__no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
}
If bindFromRequest().get() returns null, then the Form didn't validate. To debug this, log Form.form(Register.class).bindFromRequest().errors(), to see the validation errors in the Form. Beyond that no one can tell you what's wrong without seeing the Register class, and the data you're trying to bind to it.
You shouldn't be blindly calling get() on the Form and trying to save it, as this obviously can fail. At least check that it hasErrors() before trying to save it. And if it does have validation errors, you should be passing that Form back to the view to show those errors to the user.
See Handling Binding Failure in the docs.

Categories