如何将ArrayList数据映射到DTO

时间:2011-11-19 20:20:41

标签: java

根据要求,我解析了一个XML文件并将数据设置为这两个DTO类:

public class DetailsDTO implements java.io.Serializable {
private String      userid;
private String      accountnum;
private Customer    customer;
// setters and getters

public class Customer implements Serializable
{
private String            street;
private String            country;
// setters and getters

Customer课程的数据添加到DetailsDTO后,我将此DetailsDTO添加到ArrayList,如下所示:

List list = new ArrayList();
// and added these DetailsDTO class to an ArrayList
list.add(detailsDTO)

现在有一个名为WholeDetails的Master DTO,它包含在各种DTO类中定义的所有变量,如图所示。

class WholeDetails
{
private String   userid;
private String   accountnum;
private String   street;
private String   country;
}

现在,正如您所见,所有数据都在ArrayList内可用。

如何从ArrayList中提取内容并将其映射到WholeDetails

1 个答案:

答案 0 :(得分:2)

你必须进行映射,例如

List<DetailsDTO> list = new ArrayList<DetailsDTO>();    
// and added these DetailsDTO class to an ArrayList   
list.add(detailsDTO);  

List<WholeDetails> wholeDTOList = new ArrayList<WholeDetails>();   
for(DetailsDTO dto:list){  
  WholeDetails whole = new WholeDetails();  
  whole.setUserid(dto.getUserid());  
  whole.setAccountNum(dto.getAccountNum());  
  whole.setStreet(dto.getCustomer().getStreet());  
  whole.setCountry(dto.getCustomer().getCountry());  
  wholeDTOList.add(whole);

}   

如果您希望它更短,您可以创建一个适配器类,将DetailsDTO映射到WholeDetailsDTO并将结果对象添加到列表中