已经过时的方法,所以,不会调用此方法。
实体类要加注解
实体类要加注解@XStreamAlias("msg")
public class Msg implements Serializable {
private static final long serialVersionUID = 3196422897798539811L
@XStreamAsAttribute
private String toUid
@XStreamAsAttribute
private String fromUid
@XStreamAsAttribute
private String flag
@XStreamAsAttribute
private String time
@XStreamAlias("content")
private String content
@XStreamAlias("user")
private String user
//省略geter、seter
}
然后写个工具类
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
public class SerializeXmlUtil {
/**
* @param obj java对象实例
* @return String xml字符串
*/
public static String serializeToXml(Object obj) {
//XStream xstream = new XStream()
//直接用jaxp dom来解释
//XStream xstream=new XStream(new DomDriver())
//指定编码解析器,直接用jaxp dom来解释
XStream xstream=new XStream(new DomDriver("utf-8"))
//如果没有这句,xml中的根元素会是<包.类名>
//或者说:注解根本就没生效,所以的元素名就是类的属性
xstream.processAnnotations(obj.getClass())
StringBuffer xmlstrbuf = new StringBuffer()
xmlstrbuf.append("<?xml version=\"1.0\"?>")
xmlstrbuf.append("\r\n")
xmlstrbuf.append(xstream.toXML(obj))
return xmlstrbuf.toString()
}
/**
* 将传入xml字符串转化为java对象
* @param xmlstr
* @param cls xml对应的class类
* @return T xml对应的class类的实例对象
* 调用的方法实例:PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class)
*/
public static <T> T deSerizalizeFromXml(String xmlstr, Class<T> cls) throws Exception {
//注意:不是new Xstream()否则报错:java.lang.NoClassDefFoundError:
//org/xmlpull/v1/XmlPullParserFactory
XStream xstream = new XStream(new DomDriver())
xstream.processAnnotations(cls)
T obj = (T) xstream.fromXML(xmlstr)
return obj
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)