Issue
How can we return multiple entity classes as XML response in the spring rest service?
Example: I need a response like the following
<GetEmployeeById>
<Response>
<Status>0</Status>
<Message>Data found</Message>
</Response>
<Data>
<Employee>
<Id> 2 </Id>
<Name> Mani M </Name>
<Job> SOftware Developer </Job>
<Salary> 40000 </Salary>
</Employee>
</Data>
</GetEmployeeById>
Here, Response and Employee are separate entities. I am getting the following XML response with my code. The issue here is, I am getting response node inside response node and employee node inside employee node.
<GetEmployeeById>
<Response>
<Response>
<Status>0</Status>
<Message>Data found</Message>
</Response>
</Response>
<Employee>
<Employee>
<Id>2</Id>
<Name>Mani M</Name>
<Job>SOftware Developer</Job>
<Salary>12000</Salary>
</Employee>
</Employee>
</GetEmployeeById>
Following is the java class where I am combining both the entity classes.
@XmlRootElement (name="GetEmployeesById")
public class GetEmployeesById implements Serializable{
private static final long serialVersionUID = 1L;
private List<Employee> Employee = new ArrayList<Employee>();
private List<Response> Response = new ArrayList<Response>();
public List<Employee> getEmployee() {
return Employee;
}
public void setEmployee(List<Employee> employee) {
Employee = employee;
}
public List<Response> getResponse() {
return Response;
}
public void setResponse(List<Response> Response) {
Response = Response;
}
}
Kindly help me with this.
Solution
Your problem here is with List<CustomResponse>
as it is a List
, the parent </Response>
tag represents the List and child </Response>
represents the element in the List
In order to achieve your desired payload, Response
cannot be a List
and has to be CustomResponse
.
As for your data node, you might want to try creating a new class as per below
@XmlRootElement(name = "Data")
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "Employee")
private List<Employee> employees
}
You can then replace List<Employee>
with Data
in your GetEmployeesById
class
Answered By - mkjh