I have the following Employee class which i need to represent in XML format
Employee:
@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
private int id;
private String firstName;
private String lastName;
private int income;
private Map<Integer,Employee> employeeMap=new HashMap<>();
//getters and setters
}
Marshalling code:
public class MarshallExample {
public static void main(String[] args) throws JAXBException {
Map<Integer,Employee> empMap=new HashMap<>();
Employee emp1=new Employee();
emp1.setId(1);
emp1.setFirstName("aa");
emp1.setLastName("bb");
emp1.setIncome(1000);
Employee emp2=new Employee();
emp2.setId(2);
emp2.setFirstName("xx");
emp2.setLastName("yy");
emp2.setIncome(2000);
empMap.put(1, emp1);
empMap.put(2, emp2);
Employee emp=new Employee();
emp.setEmployeeMap(empMap);
JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class);
Marshaller jaxbMarshaller=jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(emp, System.out);
}
}
XML Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<id>0</id>
<income>0</income>
<employeeMap>
<entry>
<key>1</key>
<value>
<id>1</id>
<firstName>aa</firstName>
<lastName>bb</lastName>
<income>1000</income>
<employeeMap/>
</value>
</entry>
<entry>
<key>2</key>
<value>
<id>2</id>
<firstName>xx</firstName>
<lastName>yy</lastName>
<income>2000</income>
<employeeMap/>
</value>
</entry>
</employeeMap>
</employee>
Not able to figure out why the <id> 0 </id>
and <income> 0 </income>
element are present in the output inside the root element instead of just the two employee instances.
It is because that are int
values and can not be null
. Change it to Integer an they will not longer rendered.
@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
private Integer id;
private String firstName;
private String lastName;
private Integer income;
private Map<Integer,Employee> employeeMap=new HashMap<>();
//getters and Setters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.