JAVA XStream的使用
Posted 恒磊国际
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA XStream的使用相关的知识,希望对你有一定的参考价值。
MAVN包:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>
过滤不能识别的节点
package common;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.mapper.MapperWrapper;
public class ETLXstream extends XStream {
/*
* (non-Javadoc)
*
* @see
* com.thoughtworks.xstream.XStream#wrapMapper
*/
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
/*
* (non-Javadoc)
*
* @see
* com.thoughtworks.xstream.mapper.MapperWrapper#shouldSerializeMember
*/
@Override
public boolean shouldSerializeMember(@SuppressWarnings("rawtypes") Class definedIn, String fieldName) {
// 不能识别的节点,掠过。
if (definedIn == Object.class){
try {
return this.realClass(fieldName) != null;
} catch (Exception e){
return false;
}
} else {
return super.shouldSerializeMember(definedIn, fieldName);
}
}
};
}
}
XMLHelper封装类
package common;
import java.io.InputStream;
import java.lang.Class;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class XmlHelper {
public static <T> String ToXml(T object, HashMap<String, Class> map) {
ETLXstream xstream = getXStream(map);
for (Entry<String, Class> entry : map.entrySet()) {
xstream.alias(entry.getKey(), entry.getValue());
}
return xstream.toXML(object);
}
public static <T> T ToObject(String xml, HashMap<String, Class> map) {
ETLXstream xstream = getXStream(map);
T object = (T) xstream.fromXML(xml);
return object;
}
public static <T> T ToObject(InputStream stream, HashMap<String, Class> map) {
ETLXstream xstream = getXStream(map);
T object = (T) xstream.fromXML(stream);
return object;
}
private static ETLXstream getXStream(HashMap<String, Class> map) {
ETLXstream xstream = new ETLXstream();
for (Entry<String, Class> entry : map.entrySet()) {
xstream.alias(entry.getKey(), entry.getValue());
}
return xstream;
}
}
以上是关于JAVA XStream的使用的主要内容,如果未能解决你的问题,请参考以下文章
使用XStream是实现XML与Java对象的转换--简介及入门示例
使用XStream是实现XML与Java对象的转换--Object Stream