中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

XStream的使用

發布時間:2020-07-19 00:19:05 來源:網絡 閱讀:1349 作者:mybabe0312 欄目:軟件技術

本文主要用于記錄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();
}
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

桦南县| 秀山| 合作市| 锡林郭勒盟| 枣强县| 滦平县| 沐川县| 古交市| 德阳市| 南昌市| 喀喇| 新乡县| 台南市| 合肥市| 鹤庆县| 托克托县| 香格里拉县| 陆丰市| 丹寨县| 东乡族自治县| 延川县| 宝坻区| 南昌县| 嫩江县| 扎兰屯市| 马鞍山市| 广德县| 乌审旗| 昔阳县| 集安市| 米泉市| 普安县| 镇康县| 遂川县| 昌图县| 聂拉木县| 姚安县| 霍山县| 景东| 长葛市| 平罗县|