To form Json from nested POJOS - java

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

Related

How to convert JavaObject from POJO to JSONString/JSONObject

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

Pass a list of string to a declared class file

Hi All below is my Employeeinformation class file java. I have to pass the values to it through java code
I am fine passing the strings but i am unable to pass list of technologies and list of strings.
Technologies.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
#Data
public class Technologies {
private String name;
private String yearsOfExperience;
}
Employeeinformation.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
import java.util.List;
#Data
public class EmployeeInformation {
private String id;
private String firstName;
private String lastName;
private List<Technologies> technologies;
private List<String> emails;
public EmployeeInformation(String id, String firstName, String lastName, List<Technologies> technologies, List<String> emails) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.technologies = technologies;
this.emails = emails;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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<Technologies> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technologies> technologies) {
this.technologies = technologies;
}
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
}
Passing a value to class file
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali","?","?");
How to pass the list of technologies and list of string in above code. Could some one help me tho achieve this?
List<Technologies> technologies = new ArrayList<>();
technologies.add(new Technologies("name1", "1999"));
technologies.add(new Technologies("name2", "1999"));
List<String> emails = new ArrayList<>();
strs.add("one");
strs.add("two");
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali",technologies,emails);
Also add #AllArgsConstructor to Technologies class. Or use setters to init Technologies objects:
#Data
#AllArgsConstructor
public class Technologies {
private String name;
private String yearsOfExperience;
}
#Data annotation has inner #RequiredArgsConstructor. This constructor is created with all non-initialized FINAL properties.
If you have not final properties there will be empty constructor.
So you have 3 ways:
Set you fields as final: new SomeObject(List.of("1","2"));
Add #AllArgsConstuctor: result the same
Leave as it is and initialize an object by set methods
SomeObject obj = new SomeObject();
obj.setList(List.of("1", "2"));

How to map two XML element levels to one level on XStream or JAXB?

I'm facing some difficulties to map two levels of XML elements to one level in my Java Bean. Here is my context, I have one XML like this:
<?xml version='1.0' encoding="utf-8" ?>
<Employee>
<Data>
<CompanyId>1</CompanyId>
<FirstName>John</FirstName>
<LastName>Oliver</LastName>
<DOB>1986-21-07</DOB>
</Data>
</Employee>
And here is my Java Bean:
#XStreamAlias("Employee/Data")
public class Employee {
#XStreamAlias("CompanyId") private int companyId;
#XStreamAlias("FirstName") private String firstName;
#XStreamAlias("LastName") private String lastName;
#XStreamAlias("DOB") private LocalDate birthDate;
public int getCompanyId() { return companyId; }
public void setCompanyId(int companyId) { this.companyId = companyId; }
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 LocalDate getBirthDate() { return birthDate; }
public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; }
}
I put the XML elements separated by "/" just to illustrate how I want to map, but it seems XStream does not work on this way. Any trick to map using annotations or should I write a custom converter? If someone knows how to do this mapping in JAXB is also welcome.
I found a solution using JAXB + eclipselink moxy. First add the eclipselink dependency 'org.eclipse.persistence:org.eclipse.persistence.moxy:2.6.4' and to ensure you are using the eclipselink implementation in you application you need pass via command-line a JVM parameter
-Djavax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
or just set in you method main like I did:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.Month;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Employee")
public class Employee {
#XmlPath("Data/CompanyId/text()") private int companyId;
#XmlPath("Data/FirstName/text()") private String firstName;
#XmlPath("Data/LastName/text()") private String lastName;
#XmlPath("Data/DOB/text()") private LocalDate birthDate;
public int getCompanyId() { return companyId; }
public void setCompanyId(int companyId) { this.companyId = companyId; }
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 LocalDate getBirthDate() { return birthDate; }
public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; }
public String toString() {
return String.format("{companyId: %d, firstName: \"%s\", lastName: \"%s\"}", companyId, firstName, lastName);
}
public static void main(String[] args) throws Exception {
System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
Employee employee = new Employee();
employee.setCompanyId(100);
employee.setFirstName("Michael");
employee.setLastName("Hoffmann");
employee.setBirthDate(LocalDate.of(1970, Month.JANUARY, 19));
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
jaxbContext.createMarshaller().marshal(employee, out);
out.flush();
String xml = sw.toString();
System.out.println(xml);
InputStream in = new ByteArrayInputStream(xml.getBytes());
Employee employee2 = (Employee) jaxbContext.createUnmarshaller().unmarshal(in);
System.out.println(employee2);
}
}

Getters: difference between "return firstName.get();" and "return firstName;" [duplicate]

This question already has an answer here:
When to use JavaFX properties setter and getter, instead of using the property directly
(1 answer)
Closed 7 years ago.
What is the difference between these two lines?
return firstName.get();
return firstName;
When should I use one or the other?
Here you have two classes where those lines are used:
package application.model;
import javafx.beans.property.StringProperty;
public class Employee {
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 StringProperty firstNameProperty() {
return firstName;
}
}
package ch.makery.address.model;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Model class for a Person.
*
* #author Marco Jakob
*/
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty street;
private final IntegerProperty postalCode;
private final StringProperty city;
private final ObjectProperty<LocalDate> birthday;
/**
* Default constructor.
*/
public Person() {
this(null, null);
}
/**
* Constructor with some initial data.
*
* #param firstName
* #param lastName
*/
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
// Some initial dummy data, just for convenient testing.
this.street = new SimpleStringProperty("some street");
this.postalCode = new SimpleIntegerProperty(1234);
this.city = new SimpleStringProperty("some city");
this.birthday = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public String getStreet() {
return street.get();
}
public void setStreet(String street) {
this.street.set(street);
}
public StringProperty streetProperty() {
return street;
}
public int getPostalCode() {
return postalCode.get();
}
public void setPostalCode(int postalCode) {
this.postalCode.set(postalCode);
}
public IntegerProperty postalCodeProperty() {
return postalCode;
}
public String getCity() {
return city.get();
}
public void setCity(String city) {
this.city.set(city);
}
public StringProperty cityProperty() {
return city;
}
public LocalDate getBirthday() {
return birthday.get();
}
public void setBirthday(LocalDate birthday) {
this.birthday.set(birthday);
}
public ObjectProperty<LocalDate> birthdayProperty() {
return birthday;
}
}
In short: It depends on the context.
You may only use .get() when the object has a method get. String objects are very similar to primitives, they are a value and as such can be returned directly (they don't have a get method at all).
Here, StringProperty is a wrapper around (assumedly) a String, meaning if you were to return firstName; from the Person class, you would get a StringProperty instance, not a String - which most likely cannot be used in most operations. So, you return whichever datatype you need.
Note that if you were working with strings in both the source and destination classes, you could just return the value directly, it's already in usable form.

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.

Categories