码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA XStream的使用

时间:2018-04-19 11:58:09      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:ide   awt   version   define   from   rom   dna   getx   serial   

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的使用

标签:ide   awt   version   define   from   rom   dna   getx   serial   

原文地址:https://www.cnblogs.com/nation/p/8880818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!