您好,登錄后才能下訂單哦!
本文主要用于記錄XStream的使用方式,特別是其中的“對象默認值”和Map轉換器的使用
1,添加Maven依賴
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
2,創建可以使用默認值的對象
import java.lang.reflect.Field;
import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
public class FieldDefaultValueProvider extends PureJavaReflectionProvider {
/**
* @param object 目標類的實例
* @param fieldName XML中顯示指明的字段
* @param definedIn 父類或者類本身
*/
@Override
public void writeField(Object object, String fieldName, Object value, Class definedIn) {
Field field = fieldDictionary.field(object.getClass(), fieldName, definedIn);//返回存在于xml中的字段
validateFieldAccess(field);//驗證字段可以被訪問
try {
if (value instanceof String) {
String trim = ((String)value).trim();//字符串首尾去空
if(trim.length()==0)//如果是空字符串,則不做賦值,使用默認初始值
return;
field.set(object,trim);
}else{
field.set(object, value);
}
} catch (IllegalArgumentException e) {
throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
} catch (IllegalAccessException e) {
throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
}
}
}
3,創建用于轉換Map的對象
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
public class MapCustomConverter extends AbstractCollectionConverter {
public MapCustomConverter(Mapper mapper) {
super(mapper);
}
@Override
public boolean canConvert(Class type) {
return type.equals(HashMap.class) || type.equals(Hashtable.class)
|| type.getName().equals("java.util.LinkedHashMap") || type.getName().equals("sun.font.AttributeMap");
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Map map = (Map) source;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Entry entry = (Entry) iterator.next();
ExtendedHierarchicalStreamWriterHelper.startNode(writer, "property", Entry.class);
writer.addAttribute("key", entry.getKey().toString());
writer.addAttribute("value", entry.getValue().toString());
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map map = (Map) createCollection(context.getRequiredType());
populateMap(reader, context, map);
return map;
}
protected void populateMap(HierarchicalStreamReader reader, UnmarshallingContext context, Map map) {
while (reader.hasMoreChildren()) {
reader.moveDown();
Object key = reader.getAttribute("key");
Object value = reader.getAttribute("value");
map.put(key, value);
reader.moveUp();
}
}
}
4,創建XStream對象
private static XStream getXStream() {
// XStream xstream = new XStream();//需要XPP3庫
// XStream xstream = new XStream(new DomDriver());// 不需要XPP3庫
// XStream xstream = new XStream(new StaxDriver());// 不需要XPP3庫開始使用Java6
XStream xstream = new XStream(new FieldDefaultValueProvider(),new DomDriver());// 創建Xstram對象
xstream.autodetectAnnotations(true);
xstream.addPermission(AnyTypePermission.ANY);
xstream.registerConverter(
new MapCustomConverter(new DefaultMapper(new ClassLoaderReference(XStream.class.getClassLoader()))));
XStream.setupDefaultSecurity(xstream);
xstream.allowTypes(new Class[] { CollectTaskMeta.class, FtpConfig.class, TaskParallel.class,
TaskRootConfig.class, Sql.class });
xstream.processAnnotations(new Class[] { CollectTaskMeta.class, FtpConfig.class, TaskParallel.class,
TaskRootConfig.class, Sql.class });
return xstream;
}
5,使用XStream來解析文件
import org.springframework.util.ResourceUtils;
XStream xstream = getXStream();
TaskRootConfig meteInfo = null;
try {
meteInfo = (TaskRootConfig) xstream.fromXML(ResourceUtils.getFile("classpath:taskconfig.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。