Friday, 12 December 2008

xstream 1.3 ile xml'leri java objesine map etmek

Webservice veya başka bir kaynaktan gelen bir xml dökümanını xstream 1.3 library'sini kullanarak java objesine nasıl map ederiz? Bununla ilgili kısa ve basit bir örnek :

Önce datayı map edeceğimiz java bean'lerimizi oluşturalım.

public class MailHistory implements Serializable {

String responsecode;
List customerDataList = new ArrayList();

public MailHistory (final String responsecode, final CustomerData...customerDataList){
super();
this.responsecode = responsecode;
this.customerDataList = Arrays.asList(customerDataList);
}

public String getResponsecode() {
return responsecode;
}

public List getCustomerData() {
return customerDataList ;
}

}

*************************************************************************************
public class CustomerData implements Serializable {

String customerId;
String seqno;
String action;
String description;
String processdate;

public CustomerData (final String customerId, final String seqno, final String action, final String description, final String processdate) {
super();
this.customerId = customerId;
this.seqno = seqno;
this.action = action;
this.description = description;
this.processdate = processdate;
}


public String getCustomerId() {
return customerId;
}

public String getSeqno() {
return seqno;
}

public String getAction() {
return action;
}

public String getDescription() {
return description;
}

public String getProcessdate() {
return processdate;
}

}
*************************************************************************************
Oluşturduğumuz CustomerData ve MailHistory class'ları serializable olmalı, tüm parametrelerden oluşan bir constructer'ı bulunmalı, ve get'ter metodları bulunmalıdır.


import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class TestJava{

public static void main(String[] args) throws Exception {




// initialize xstream
XStream xstream = new XStream(new DomDriver());

// alias classes
xstream.alias("MAILHISTORY",MailHistory.class);
xstream.alias("CustomerData",CustomerData.class);
xstream.aliasField("RESPONSECODE", CustomerHistory.class, "responsecode");
xstream.aliasField("CUSTOMERDATA", CustomerHistory.class, "customerDataList");
xstream.addImplicitCollection(MailHistory.class, "customerDataList", CustomerData.class);
xstream.aliasField("CUSTOMERID", CustomerData.class, "customerId");
xstream.aliasField("SEQNO", CustomerData.class, "seqno");
xstream.aliasField("ACTION", CustomerData.class, "action");
xstream.aliasField("DESCRIPTION", CustomerData.class, "description");
xstream.aliasField("PROCESSDATE", CustomerData.class, "processdate");


MailHistory mailHistory = (MailHistory) xstream.fromXML(myxml);
System.out.println(xstream.toXML(mailHistory));
}
}

Not: XStream 1.3 anotasyonları da desteklemektedir. Daha fazla bilgi edinmek isterseniz. Xtream tutorials'ı ziyaret edebilirsiniz.