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;
}
}