How to convert JavaObject from POJO to JSONString/JSONObject - java

I have a POJO which returns JAVAObject , Now I want to convert it to JSONObject but my POJO contains an array which is not converted using below code:
Email Class:
package pojo;
public class Email {
String TYPE;
String VALUE;
public Email() {
}
public Email(String TYPE, String VALUE) {
this.TYPE = TYPE;
this.VALUE = VALUE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTYPE() {
return this.TYPE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
public String getVALUE() {
return this.VALUE;
}
}
PostAccountCreateAPI Class:
package pojo;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class PostAccountCreateAPI {
private String FirstName;
private String LastName;
private String PASSWORD;
private List<Email> Email;
static List<Email> emailList = new ArrayList<>();
public PostAccountCreateAPI() {
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getFirstName() {
return this.FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getLastName() {
return this.LastName;
}
public void setPASSWORD(String PASSWORD) {
this.PASSWORD = PASSWORD;
}
public String getPASSWORD() {
return this.PASSWORD;
}
public void setEmail(List<Email> Email) {
this.Email = Email;
}
public List<Email> getEmail() {
return this.Email;
}
}
I have created the Object of PostAccountCreateAPI Class and converting to JSONString as below:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(postAccountCreateAPI);
System.out.println(json);
But I am not getting Email as array, Below is the response I got:
{"lastName":null,"email":null,"firstName":null,"password":null}
I am expecting it in below format:
"FirstName": "FSFBE",
"LastName": "LoUSj",
"PASSWORD": "p#$$word123",
"Email": [
{
"TYPE": "Primary",
"VALUE": "test7EZK0#mail7.io"
}
]
}

It looks like there is something wrong with your postAccountCreateAPI initialization. Can you please copy the line, where you call the constructor and/or set the attributes?
Plus I think you should follow the java naming convention. You violate almost every rule.
https://www.javatpoint.com/java-naming-conventions

Related

Not able to wrap JSON properties in a Custom Java Class in Jackson

I have a JSON string that needs to be converted to JAVA Object. I need to wrap some fields into a different JAVA class. The problem I am facing I am not able to wrap it and I get the Java fields as null.
Please see below JSON
{
"first_name": "John",
"last_name": "DCosta",
"age": "29",
"phone": "+173341238",
"address_line_1": "43 Park Street",
"address_line_2": "Behind C21 Mall",
"city": "Cario",
"country": "UK",
"child1": {
"name": "Peter",
"age": "5"
},
"child2": {
"name": "Paddy",
"age": "2"
},
"child3": {
"name": "Premus",
"age": "1"
}
}
Please see my JAVA Classes Below -
Details.java
public class Details {
private Person person;
private Address address;
private Child[] children;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Child[] getChildren() {
return children;
}
public void setChildren(Child[] children) {
this.children = children;
}
}
Person.java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
#JsonProperty("first_name")
private String firstName;
#JsonProperty("last_name")
private String lastName;
#JsonProperty("age")
private Integer age;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Address.java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Address {
#JsonProperty("phone")
private String phone;
#JsonProperty("address_line_1")
private String addressLine1;
#JsonProperty("address_line_2")
private String addressLine2;
#JsonProperty("city")
private String city;
#JsonProperty("country")
private String country;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Child.java
public class Child {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
My Code to convert JSON to JAVA Object -
String filePath = "test.json";
File file = new File(filePath);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Details details = mapper.readValue(file, Details.class);
System.out.println(details.getPerson());
The problem I am facing is I am getting all the values in the details object are null. If I remove the mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); then I get the below exception
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "first_name" (class learn.springboot.model.Details), not marked as ignorable (3 known properties: "address", "person", "children"])
at [Source: (File); line: 2, column: 17] (through reference chain: learn.springboot.model.Details["first_name"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.ja
I don't think that it is possible to have some wrapper classes and expect Jackson to flatten and extract all of those fields from wrapper classes and map the flat JSON fields to them.
Based on the Details class, Jackson expects having a JSON object like the below one (inner fields are omitted):
{
"person": {},
"address": {},
"children": []
}
So, you have to change the Details class to something like below:
public class Details {
#JsonProperty("first_name")
private String firstName;
#JsonProperty("last_name")
private String lastName;
#JsonProperty("age")
private Integer age;
...
}

How to map JSONObject in Java object

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;

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.

To form Json from nested POJOS

I have nested POJO as below. All the POJO's are in the same package. Please see student is is the name pojo and all other POJO are inside
class Student{
String firstName;
String lastName;
List <Activities> activites;
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 List<Activities> getActivites() {
return activites;
}
public void setActivites(List<Activities> activites) {
this.activites = activites;
}
}
class Activites{
List<Quipments> quipments;
String time;
public List<Quipments> getQuipments() {
return quipments;
}
public void setQuipments(List<Quipments> quipments) {
this.quipments = quipments;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
class Quipments{
String Type;
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
}
I want to convert the above student POJO in json that will have all the values of other pojo.
We are not suppose to use below api. I know the below one works.
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
Want to use something like below
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
Please advice
Use this very popular library https://github.com/google/gson:
String sample = "{firstName: \"mardar\", lastName: \"pandit\"}";
com.google.gson.Gson gson = new com.google.gson.Gson();
Student student = gson.fromJson(sample, Student.class);
System.out.println(gson.toJson(student));

Categories