网站建设资讯

NEWS

网站建设资讯

XStream的使用

本文主要用于记录XStream的使用方式,特别是其中的“对象默认值”和Map转换器的使用

十多年的苏尼特右网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网整合营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整苏尼特右建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“苏尼特右网站设计”,“苏尼特右网站推广”以来,每个客户项目都认真落实执行。

1,添加Maven依赖


          com.thoughtworks.xstream
          xstream
          1.4.11.1

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

本文题目:XStream的使用
URL网址:http://cdweb.net/article/ppdjgh.html