Survive by day and develop by night.
talk is cheap, show me the code,make a better result.
目录
概述
在webservice 中常见的解析为bean 的工具类
需求:
1.xmltobean
设计思路
实现思路分析
1.xml2bean
//指定所有class均解析annotations
xstream.autodetectAnnotations(true);
//指定指定class解析annotations
xstream.processAnnotations(People.class);
//
使用xstream自带的NoNameCoder构造xstream,该方式将导致所有特殊字符都不转义
XStream xstream = new XStream(new XppDriver(new NoNameCoder()));
//使用Domdriver及NonameCoder构造xstream,该方式可以指定xml编码方式
XStream xstream = new XStream(new DomDriver(“UTF-8”, new NoNameCoder()));
new Xstream().toXML(bean);
xstreams Utils 的封装:
package com.hibase.common.utils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* xstream工具类
*
* @author hufeng
* @date 2019/07/09
*/
public class XStreamUtils {
private XStreamUtils() {
}
/**
* 通过静态内部类实现单例模式
*/
private static class LazyHolder {
private static final XStreamUtils INSTANCE = new XStreamUtils();
}
private static class SingletonXstream {
private static XStream xStream = null;
static {
if (xStream == null) {
xStream = new XStream(new DomDriver());
// 去掉class属性
xStream.aliasSystemAttribute(null, "class");
//避免出现以下警告:Security framework of XStream not initialized, XStream is probably vulnerable
XStream.setupDefaultSecurity(xStream);
}
}
}
public static XStream getInstance() {
return SingletonXstream.xStream;
}
/**
* 对象直接转换为XML字符串格式
*
* @param t
* @param <T>
* @return
*/
public static <T> String toXml(T t) {
XStream xstream = XStreamUtils.getInstance();
xstream.allowTypeHierarchy(t.getClass());
xstream.processAnnotations(t.getClass());
return xstream.toXML(t);
}
/**
* XML直接转化为对象
*
* @param xml
* @param clazz
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T toBean(String xml, Class<T> clazz) {
XStream xstream = XStreamUtils.getInstance();
xstream.allowTypeHierarchy(clazz);
xstream.processAnnotations(clazz);
T obj = (T) xstream.fromXML(xml);
return obj;
}
}
拓展实现
这里参考:github:简单实现上述流程:
入门级实现:
: 部分源码实现.
: 源码实现
性能参数测试:
无,暂时没有
参考资料和推荐阅读
欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~