XStream 序列化与反序列化
一直以来写代码的时候都是不断地复制、粘贴。代码写多了,时间长了,不看代码根本就不知道代码的具体实现的方式是什么,现在对以前写过的代码进行一个简单的整理。
- xstream的jar文件下载路径
- 对象的创建
- 具体的Xstream的实现方式
- 具体事例说明
xstream的jar文件下载路径
- 云盘:
- 官网:
对象的创建
@XStreamAlias("Body")
public class Login {
@XStreamAlias("Request")
public Request request = null;
@XStreamAlias("Response")
public Response response = null;
public static class Request implements IDto {
@XStreamAlias("Code")
@XStreamAsAttribute
public String orgCode;
@XStreamAlias("Type")
@XStreamAsAttribute
public String operType;
@XStreamAlias("UserN")
public String userN = "";
@XStreamAlias("PassWord")
public String password = "";
}
public static class Response implements IDto {
@XStreamAlias("ErrMsg")
@XStreamAsAttribute
public String errMsg = "";
@XStreamAlias("UserID")
public String userID = "";
@XStreamAlias("PassWord")
public String passWord = "";
@XStreamAlias("UserName")
public String userName = "";
@XStreamAlias("RoleCD")
public String roleCD = "";
@XStreamAlias("RoleName")
public String roleName = "";
@XStreamAlias("UserType")
public String userType = "";
@XStreamAlias("Station")
@XStreamConverter(BeanCDConverter.class)
public BeanCD station = null;
@XStreamAlias("Country")
@XStreamConverter(BeanCDConverter.class)
public BeanCD country = null;
@XStreamAlias("Province")
@XStreamConverter(BeanIDConverter.class)
public BeanID province = null;
@XStreamAlias("City")
@XStreamConverter(BeanIDConverter.class)
public BeanID city = null;
@XStreamAlias("District")
@XStreamConverter(BeanIDConverter.class)
public BeanID district = null;
@XStreamAlias("Street")
@XStreamConverter(BeanIDConverter.class)
public BeanID street = null;
@XStreamAlias("Community")
@XStreamConverter(BeanCDConverter.class)
public BeanCD community = null;
@XStreamAlias("Lane")
public String lane = "";
@XStreamAlias("Other")
public String other = "";
@XStreamAlias("CommunityJurisdiction")
@XStreamConverter(BeanCDConverter.class)
public BeanCD communityJuris = null;
@XStreamAlias("Zones")
public Zones Zone;
public static class Zones{
@XStreamImplicit(itemFieldName="Zone" )
public List<ZoneID> zoneIDs;
}
}
}
具体实现事例
在XmlSeriaUtil类中的两个对XStream的调用方法
/**
*对象转换成字符串
**/
public static String beanToXml(Object obj) {
String xml = null;
try {
XStream xstream = new XStream();
xstream.processAnnotations(obj.getClass());
xml = xstream.toXML(obj);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
/**
*字符串转换成相应的类
**/
public static <T> T xmlToBean(String xml, Class<T> clazz) {
try {
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(clazz);
xstream.ignoreUnknownElements();
T obj = (T) xstream.fromXML(xml);
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
具体调用方法
XmlSeriaUtil.xmlToBean(str, Login.class);
Login login = new Login();
String str = XmlSeriaUtil.beanToXml(login);