日期:2014-05-16  浏览次数:20449 次

用xStream+jettsion解析RESTEasy生成的包含自定义类型List的JSON`

1,配置服务器端

?

?

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "BusStationInfos")
public class BusStationInfos {
	@XmlElementWrapper(name="BusStationInfoList")
	@XmlElement(name = "BusStationInfo")
	private ArrayList<BusStationInfo> busStationInfoList;

	public ArrayList<BusStationInfo> getBusStationInfoList() {
		return busStationInfoList;
	}

	public void setBusStationInfos(ArrayList<BusStationInfo> busStationInfoList) {
		this.busStationInfoList = busStationInfoList;
	}

}

?

其中@XmlElementWrapper(name="BusStationInfoList")是BusStationInfo的包装类·用来在解析里对应一个ArrayList对象

?

生成的JSON如下:

写道
{"BusStationInfos":{
"BusStationInfoList":{
"BusStationInfo":[
{"chartered1":0,"charteredGrowth":0,"stationName":"鍖楀尯"},
{"chartered1":0,"charteredGrowth":0,"stationName":"鍗楀尯"}
]
}
}}
?

2 客户端:

?

XStream xstream = new XStream(new JettisonMappedXmlDriver());
		xstream.alias("BusStationInfos", BusStationInfos.class);
		xstream.alias("BusStationInfoList", ArrayList.class);
		xstream.alias("BusStationInfo", BusStationInfo.class);
		
		
		

		BusStationInfos busStationInfos = (BusStationInfos) xstream
				.fromXML(jsonString);

?

当初没有在服务器端添加@XmlElementWrapper·怎么也解析不出来·现在·这样配置就OK了··