XML文件如下:
<MbfBody>
<price>
<cmmdtyCode>1</cmmdtyCode>
<cityCode>1</cityCode>
<storeCode>s</storeCode>
<cmmdtyPrice>56</cmmdtyPrice>
<oneExtendPrice>56</oneExtendPrice>
<twoExtendPrice>56</twoExtendPrice>
<threeExtendPrice>56</threeExtendPrice>
<downTime>2012-12-12</downTime>
</price>
<price>
<cmmdtyCode>2</cmmdtyCode>
<cityCode>1</cityCode>
<storeCode>s</storeCode>
<cmmdtyPrice>56</cmmdtyPrice>
<oneExtendPrice>56</oneExtendPrice>
<twoExtendPrice>56</twoExtendPrice>
<threeExtendPrice>56</threeExtendPrice>
<downTime>2012-12-12</downTime>
</price>
</MbfBody>
想使用XStream转换为bean。
只需要使用@XStreamImplicit(itemFieldName="price")即可。
代码如下:
/**
*
* @author freedwindx
*/
@XStreamAlias("MbfBody")
public class XPriceDownloadItemList extends BaseDto{
/**
*/
private static final long serialVersionUID = -4942613159612187126L;
@XStreamImplicit(itemFieldName="price")//这句话是关键
private List<XPriceDownloadItem> downloadItems;
/**
*
*/
public XPriceDownloadItemList() {
// TODO Auto-generated constructor stub
}
/**
* @param downloadItems
*/
public XPriceDownloadItemList(List<XPriceDownloadItem> downloadItems) {
super();
this.downloadItems = downloadItems;
}
/**
* @param downloadItems the downloadItems to set
*/
public void setDownloadItems(List<XPriceDownloadItem> downloadItems) {
this.downloadItems = downloadItems;
}
/**
* @return the downloadItems
*/
public List<XPriceDownloadItem> getDownloadItems() {
return downloadItems;
}
上面是list,还需要一个对bean的注解。
/**
*
* 功能描述:
*
* @author 作者
* @created 2013-12-24 上午9:08:12
* @version 1.0.0
* @date 2013-12-24 上午9:08:12
*/
@XStreamAlias("price")
public class XPriceDownloadItem extends BaseDto {
private static final long serialVersionUID = 3803940743664353143L;
@XStreamAlias("cmmdtyCode")
private String cmmdtyCode;
@XStreamAlias("cityCode")
private String cityCode;
@XStreamAlias("storeCode")
private String storeCode;
@XStreamAlias("cmmdtyPrice")
private String cmmdtyPrice;
@XStreamAlias("oneExtendPrice")
private String oneExtendPrice;
@XStreamAlias("twoExtendPrice")
private String twoExtendPrice;
@XStreamAlias("threeExtendPrice")
private String threeExtendPrice;
@XStreamAlias("downTime")
private String downTime;
main函数:
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.autodetectAnnotations(true);
XPriceDownloadItemList xPriceDownloadItemList = new XPriceDownloadItemList();
List<XPriceDownloadItem> list = new ArrayList<XPriceDownloadItem>();
XPriceDownloadItem x1 = new XPriceDownloadItem("1", "1", "s","56", "56", "56", "56", "2012-12-12");
XPriceDownloadItem x2 = new XPriceDownloadItem("2", "1", "s","56", "56", "56", "56", "2012-12-12");
list.add(x1);
list.add(x2);
xPriceDownloadItemList.setDownloadItems(list);
String str = xStream.toXML(xPriceDownloadItemList);
System.out.println(str);
XPriceDownloadItemList x22 = (XPriceDownloadItemList) xStream.fromXML(str);
System.out.println(x22.getDownloadItems().size());
}