How to customise an XML export using JAXB - java

For testing purposes, I used used JAXB to generate an XML from an Object. This work fine. The code is below.
package com.mns.mnsutilities.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="Emp_MNS")
#XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "gen")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// #XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElement(name = "addresses")
public List<Address> getAddressesList() {
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
#Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
And:
package com.mns.mnsutilities.jaxb.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(namespace="")
public class Address {
private String street;
private String city;
private String zipCode;
private String country;
public Address() {}
public Address(String street, String city, String zipCode, String country) {
super();
this.street = street;
this.city = city;
this.zipCode = zipCode;
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", zipCode="
+ zipCode + ", country=" + country + "]";
}
}
My main Class is :
package com.mns.mnsutilities.jaxb.batch;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.mns.mnsutilities.jaxb.model.Address;
import com.mns.mnsutilities.jaxb.model.Employee;
public class LaunchAction {
private static final String FILE_NAME = "output/CT3D_XML_SAMPLE_FINAL.xml";
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(1);
emp.setAge(25);
emp.setName("Yovan");
emp.setGender("Male");
emp.setRole("Developer");
emp.setPassword("sensitive");
List<Address> addressesList = new ArrayList<>();
Address address1 = new Address("Main Road", "Ebene", "11111", "Mauritius");
Address address2 = new Address("Royal Road", "Rose-Hill", "2222", "Mauritius");
addressesList.add(address1);
addressesList.add(address2);
emp.setAddressesList(addressesList);
jaxbObjectToXML(emp);
Employee empFromFile = jaxbXMLToObject();
System.out.println(empFromFile.toString());
}
private static Employee jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller un = context.createUnmarshaller();
Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
return emp;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
private static void jaxbObjectToXML(Employee emp) {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
//for pretty-print XML in JAXB
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out for debugging
m.marshal(emp, System.out);
// Write to File
m.marshal(emp, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
The XML output is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
</addresses>
<addresses>
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
</addresses>
</Emp_MNS>
What I really would like to have is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
**<address>**
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
**</address>**
**<address>**
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
**</address>**
</addresses>
</Emp_MNS>
Could you please guide me on how to proceed?

You can do the following:
#XmlElementWrapper(name="addresses")
#XmlElement(name="address")
public List<Address> getAddressesList() {

Related

Even after using #AttributeOverrides to change attribute names, I am still getting Repeated Column error

package com.hashedin.employeemanagementsystem.entities;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Data
#Table(name="employee")
#Entity(name="User")
public class User{
public User(){
this.individual = new Individual();
this.workExperience = null;
this.experienceInMonths = null;
this.jobRole = null;
this.primaryContact = null;
this.secondaryContact = null;
this.employeeID = null;
this.joiningDate = null;
this.employeeCategory = null;
this.exitDate = null;
this.educationDetails = null;
}
#Id
//Employee 4 digit ID
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="employee_id")
private Long empID;
//employee ID Code
#Column(name = "employee_code_id")
private String employeeID;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="first_name", column = #Column(name="employee_first_name")),
#AttributeOverride(name="last_name", column = #Column(name="employee_last_name")),
#AttributeOverride(name="email", column = #Column(name="employee_email")),
#AttributeOverride(name="phone", column = #Column(name="employee_phone")),
})
private Individual individual;
//Primary and Secondary Contacts
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "email", column = #Column(name = "primary_contact_email")),
#AttributeOverride(name = "Individual.first_name", column = #Column(name = "primary_contact_first_name")),
#AttributeOverride(name = "last_name", column = #Column(name = "primary_contact_last_name")),
#AttributeOverride(name = "phone", column = #Column(name = "primary_contact_phone"))
})
private Individual primaryContact;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="email", column = #Column(name="secondary_contact_email")),
#AttributeOverride(name="first_name", column=#Column(name="secondary_contact_first_name")),
#AttributeOverride(name="last_name", column=#Column(name="secondary_contact_last_name")),
#AttributeOverride(name="phone", column=#Column(name="secondary_contact_phone"))
})
private Individual secondaryContact;
//jobRole
#Embedded
private JobRole jobRole;
//joining date and exit date (mentioned for Fixed Employees / probation period)
#Column(name="joining_date")
private Date joiningDate;
#Column(name="exit_date")
private Date exitDate;
//category, experience and highest degree
#OneToOne(cascade = CascadeType.ALL)
private Education educationDetails;
#Column(name="employee_category")
private String employeeCategory;
#Column(name="total_experience")
private Integer experienceInMonths;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="employee_id")
private List<Employment> workExperience;
public User(String firstName, String lastName, Location location, String email, String phone, String employeeID, Individual primaryContact, Individual secondaryContact, Date joiningDate, String employeeCategory, Date exitDate, Integer experience, Education educationDetails, JobRole jobRole, List<Employment> exp) {
this.individual = new Individual(firstName, lastName, location, email, phone);
this.workExperience = exp;
this.experienceInMonths = experience;
this.jobRole = jobRole;
this.primaryContact = primaryContact;
this.secondaryContact = secondaryContact;
this.employeeID = employeeID;
this.joiningDate = joiningDate;
this.employeeCategory = employeeCategory;
this.exitDate = exitDate;
this.educationDetails = educationDetails;
}
public Individual getIndividual() {
return individual;
}
public void setIndividual(Individual individual) {
this.individual = individual;
}
public Long getEmpID() {
return empID;
}
public void setEmpID(Long empID) {
this.empID = empID;
}
public Integer getExperienceInMonths() {
return experienceInMonths;
}
public void setExperienceInMonths(Integer experienceInMonths) {
this.experienceInMonths = experienceInMonths;
}
public List<Employment> getWorkExperience() {
return workExperience;
}
public void setWorkExperience(List<Employment> workExperience) {
this.workExperience = workExperience;
}
public JobRole getJobRole() {
return jobRole;
}
public void setJobRole(JobRole jobRole) {
this.jobRole = jobRole;
}
public Education getEducationDetails() {
return educationDetails;
}
public void setEducationDetails(Education educationDetails) {
this.educationDetails = educationDetails;
}
public Integer getExperience() {
return experienceInMonths;
}
public void setExperience(Integer experience) {
this.experienceInMonths = experience;
}
public Date getExitDate() {
return exitDate;
}
public void setExitDate(Date exitDate) {
this.exitDate = exitDate;
}
public String getEmployeeCategory() {
return employeeCategory;
}
public void setEmployeeCategory(String employeeCategory) {
this.employeeCategory = employeeCategory;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
public Individual getPrimaryContact() {
return primaryContact;
}
public void setPrimaryContact(Individual primaryContact) {
this.primaryContact = primaryContact;
}
public Individual getSecondaryContact() {
return secondaryContact;
}
public void setSecondaryContact(Individual secondaryContact) {
this.secondaryContact = secondaryContact;
}
#Override
public String toString() {
return "User{" +
"empID=" + empID +
", employeeID='" + employeeID + '\'' +
", individual=" + individual.toString() +
", primaryContact=" + primaryContact +
", secondaryContact=" + secondaryContact +
", jobRole=" + jobRole +
", joiningDate=" + joiningDate +
", exitDate=" + exitDate +
", educationDetails=" + educationDetails +
", employeeCategory='" + employeeCategory + '\'' +
", experienceInMonths=" + experienceInMonths +
", workExperience=" + workExperience +
'}';
}
}
Still getting this error, please help:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boo
t/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceU
nit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.hashedin.emplo
yeemanagementsystem.entities.User column: email (should be mapped with insert="false" update="false")
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5
.3.5.jar:5.3.5]
This is what my Individual class looks like:
package com.hashedin.employeemanagementsystem.entities;
import javax.persistence.*;
import java.lang.annotation.Target;
#Embeddable
public class Individual {
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Embedded
private Location location;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
public Individual(){
this.firstName="";
this.lastName="";
this.location=null;
this.email=null;
this.phone=null;
}
public Individual(String firstName, String lastName, Location location, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.location = location;
this.email = email;
this.phone = phone;
}
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 Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return "Individual{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", location=" + location +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}

Using aggregation with Spring JDBC

I am learning Spring JDBC inserting to database but I could not insert my 2 aggregated classes together. (Employee which has Address class). How can I add Address class' variables to Employee table? Code below, thanks.
Employee.java
package model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Employee {
private int id;
private String name;
private String surname;
private int age;
private String gender;
private String contact;
public Employee(int id, String name, String surname, int age, String gender, String contact, Address address) {
super();
this.id = id;
this.name = name;
this.surname = surname;
this.age = age;
this.gender = gender;
this.contact = contact;
this.address = address;
}
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", surname=" + surname + ", age=" + age + ", gender=" + gender
+ ", contact=" + contact + ", address=" + address + "]";
}
}
Address.java
package model;
public class Address {
private String address;
private String city;
private String country;
public Address(String address, String city, String country) {
super();
this.address = address;
this.city = city;
this.country = country;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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;
}
#Override
public String toString() {
return "[" + address + ", city=" + city + ", country=" + country + "]";
}
}
EmployeeDAO.java
package dao;
import java.sql.SQLException;
import model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee) throws Exception;
}
EmployeeDAOImpl.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.stereotype.Repository;
import model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private final static String INSERT_EMPLOYEE = "insert into employee (id, name, surname, age, gender, contact) values (?,?,?,?,?,?)";
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public void saveEmployee(Employee employee) throws SQLException {
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_EMPLOYEE);
preparedStatement.setInt(1, employee.getId());
preparedStatement.setString(2, employee.getName());
preparedStatement.setString(3, employee.getSurname());
preparedStatement.setInt(4, employee.getAge());
preparedStatement.setString(5, employee.getGender());
preparedStatement.setString(6, employee.getContact());
//index 7,8 and 9 are address, city and country...
preparedStatement.executeUpdate();
preparedStatement.close();
System.out.println("Employee is inserted..." + employee);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>myconfiguration/jdbc.properties</value>
</property>
</bean>
<bean id="dataSourceId"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="employeeDAOImplId" class="dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSourceId" />
</bean>
</beans>
MainTest.java
package test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.EmployeeDAO;
import model.Employee;
public class MainTest {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("EmployeeJDBC.xml");
EmployeeDAO dao = context.getBean(EmployeeDAO.class);
Employee employee = new Employee(1, "John", "Doe", 24, "M", "+15555555555", null); // here null, i couldn't fix.
// Address address = new Address("RandAddress", "RandCity", "RandCountry");
dao.saveEmployee(employee);
}
}
By your design, you should be able just to add appropriate columns to the insert query, and update parameters:
// EmployeeDAOImpl
private final static String INSERT_EMPLOYEE = "insert into employee (id, name, surname, age, gender, contact, address, city, country) values (?,?,?,?,?,?,?,?,?)";
// ...
#Override
public void saveEmployee(Employee employee) throws SQLException {
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_EMPLOYEE);
preparedStatement.setInt(1, employee.getId());
preparedStatement.setString(2, employee.getName());
preparedStatement.setString(3, employee.getSurname());
preparedStatement.setInt(4, employee.getAge());
preparedStatement.setString(5, employee.getGender());
preparedStatement.setString(6, employee.getContact());
//index 7,8 and 9 are address, city and country...
preparedStatement.setString(7, employee.getAddress().getAddress());
preparedStatement.setString(8, employee.getAddress().getCity());
preparedStatement.setString(9, employee.getAddress().getCountry());
preparedStatement.executeUpdate();
preparedStatement.close();
System.out.println("Employee is inserted..." + employee);
} catch (SQLException e) {
e.printStackTrace();
}
}
And set the fields in MainTest:
public class MainTest {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("EmployeeJDBC.xml");
EmployeeDAO dao = context.getBean(EmployeeDAO.class);
Address address = new Address("RandAddress", "RandCity", "RandCountry");
Employee employee = new Employee(1, "John", "Doe", 24, "M", "+15555555555", address);
dao.saveEmployee(employee);
}
}

CSV file does not open correctly on Mac computers

I am using jackson-dataformat-csv library to generate a csv file but I am cannot open it correctly on Mac Computers. Here is the java code to generate csv, I do not know what I am doing wrong here:
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CsvDownload {
public static void main(String[] args) throws IOException {
User user1 = new User("Cow",25, "xxxxxx#gmail.com","1234567890",
"Street","Heights","7100",
"Male","Town");
User user2 = new User("John",26, "xxxxxxx#gmail.com","+1234567890",
"Street","Heights","7100",
"Male","Town");
List<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);
// create mapper and schema
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(User.class).withHeader();
schema = schema.withColumnSeparator(',');
// output writer
ObjectWriter myObjectWriter = mapper.writer(schema);
File tempFile = new File("users.csv");
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(tempFileOutputStream, 1024);
OutputStreamWriter writerOutputStream = new
OutputStreamWriter(bufferedOutputStream, "UTF-8");
myObjectWriter.writeValue(writerOutputStream, users);
}
}
Model class:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder(value = {"name", "age", "email", "phone_number",
"physical_address", "postal_address", "postal_code",
"gender", "city"})
public class User {
#JsonProperty("Name")
private String name;
#JsonProperty("Age")
private int age;
#JsonProperty("Email Address")
private String email;
#JsonProperty("Phone Number")
private String phone_number;
#JsonProperty("Physical Address")
private String physical_address;
#JsonProperty("Postal Address")
private String postal_address;
#JsonProperty("Postal Code")
private String postal_code;
#JsonProperty("Gender")
private String gender;
#JsonProperty("City")
private String city;
public User(String name, int age, String email, String phone_number, String
physical_address, String postal_address, String postal_code, String gender,
String city) {
this.name = name;
this.age = age;
this.email = email;
this.phone_number = phone_number;
this.physical_address = physical_address;
this.postal_address = postal_address;
this.postal_code = postal_code;
this.gender = gender;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getPhysical_address() {
return physical_address;
}
public void setPhysical_address(String physical_address) {
this.physical_address = physical_address;
}
public String getPostal_address() {
return postal_address;
}
public void setPostal_address(String postal_address) {
this.postal_address = postal_address;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
This the code I am using to generate a csv file but does not open right on Mac computers, I do not have issues on windows.
Screen image

Produce JSON with name of the object from REST web services in Java

I wrote a REST web service which is returning JSON as below
[{"id":0,"name":"Vishal","age":"23","dob":"21/1/1992","phone":"9966558","sslc":"90","hsc":"90","college":"90"},
{"id":0,"name":"Karthik","age":"27","dob":"14/8/1988","phone":"995674","sslc":"99","hsc":"100","college":"100"},
{"id":0,"name":"Jeeva","age":"29","dob":"10/1/1987","phone":"77422","sslc":"99","hsc":"99","college":"100"},
{"id":0,"name":"Arya","age":"26","dob":"10/1/1989","phone":"55668","sslc":"100","hsc":"99","college":"99"}]
But I want the output with the "student" appended as below.
{"student":[{"id":0,"name":"Vishal","age":"23","dob":"21/1/1992","phone":"9966558","sslc":"90","hsc":"90","college":"90"},
{"id":0,"name":"Karthik","age":"27","dob":"14/8/1988","phone":"995674","sslc":"99","hsc":"100","college":"100"},
{"id":0,"name":"Jeeva","age":"29","dob":"10/1/1987","phone":"77422","sslc":"99","hsc":"99","college":"100"},
{"id":0,"name":"Arya","age":"26","dob":"10/1/1989","phone":"55668","sslc":"100","hsc":"99","college":"99"}]}
how can I achieve this output?
Below is the Product Class
#XmlRootElement(name="student")
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public Student() {
super();
}
public Student(int id, String name, String age, String dob, String phone,
String sslc, String hsc, String college) {
super();
this.id = id;
this.name = name;
this.age = age;
this.dob = dob;
this.phone = phone;
this.sslc = sslc;
this.hsc = hsc;
this.college = college;
}
private int id;
private String name;
private String age;
private String dob;
private String phone;
private String sslc;
private String hsc;
private String college;
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#XmlElement
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
#XmlElement
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#XmlElement
public String getSslc() {
return sslc;
}
public void setSslc(String sslc) {
this.sslc = sslc;
}
#XmlElement
public String getHsc() {
return hsc;
}
public void setHsc(String hsc) {
this.hsc = hsc;
}
#XmlElement
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", dob=" + dob + ", phone=" + phone + ", sslc=" + sslc
+ ", hsc=" + hsc + ", college=" + college + "]";
}
}
Below is the service class.
#GET
#Path("/student.srv")
#Produces("application/json")
public Response getStudentJson(){
DAOLayer daoLayer=new DAOLayer();
List<Student> studentsList=null;
try {
studentsList=daoLayer.getStudents();
} catch (SQLException e) {
e.printStackTrace();
}
return Response.ok(studentsList).build();
}
Kindly help me to achieve the above mentioned output.
Thanks in Advance.
To get the desired output, you will have to create one single root object containing a List<Student> student and return it:
Root.java
#XmlRootElement(name="root")
public class Root implements Serializable {
#XmlList
private List<Student> student = new ArrayList<Student>();
// getter and setter
}
Service.java
#GET
#Path("/student.srv")
#Produces("application/json")
public Response getStudentJson(){
DAOLayer daoLayer=new DAOLayer();
List<Student> studentsList=null;
try {
studentsList=daoLayer.getStudents();
} catch (SQLException e) {
e.printStackTrace();
}
Root root = new Root();
root.setStudent(studentsList),
return Response.ok(root).build();
}

JAXB - Prevent nillable attributes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"

Here is my problem: I need the name tag of by object to be present in the XML but without the nillable attributes : In short like <name/>. Here is the code for the object.
If name is null, I do get the tag <name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>, but the additional attributes may cause problem to the client.
As I have read, semantically it does make sense to represent the null values this way (using #XmlElement(nillable=true)).
package com.mns.mnsutilities.jaxb.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name="Emp_MNS")
#XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "gen", nillable=true)
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElementWrapper( name="addresses" )
#XmlElement(name = "address")
public List<Address> getAddressesList() {
if(addressesList == null){
addressesList = new ArrayList<>();
}
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
#Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
Expanding on the comment made by Ian Roberts you could leverage field access and have the property treat a field value of "" as null.
#XmlRootElement(name="Emp_MNS")
#XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
private String name = "";
public String getName() {
if(name.length() == 0) {
return null;
}
return name;
}
public void setName(String name) {
if(null == name) {
this.name = "";
} else {
this.name = name;
}
}
i got the same problem,But my field is enum,It can't be emyty string;so I just use
myXml.replaceAll("xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"","")
in another solution,I add a empty string value to my enum,such as
#XmlEnum
#Getter
public enum MyEnum {
#XmlEnumValue("1") Apple("1"),
#XmlEnumValue("2") Banner("2"),
#XmlEnumValue("") NULL("3");
MyEnum(String value, String description) {
this.value = value;
this.description = description;
}
private String value;
private String description;
}
so that I can set MyEnum.NULL to filed;

Categories

Resources