xmlstream格式转化Java类

一.代码如下:此外注意引入xstreamjar包

//@XStreamAlias 别名注解;
    //@XStreamAsAttribute//转换成属性,而不是子标签
    //@XStreamOmitField 忽略字段
    //@XStreamConverter注入转换器(转换器要求无参构造器)
    //@XStreamImplicit 忽略集合名称标签
    /**
     * 将Java类转化为string状态的xml代码
     * @param o 参数·
     * @return 返回数·
     */
    public static String toXml(Object o){
        XStream xStream=new XStream();
        //自动加载所有XStream注解的bean,与上面的区别是上面加载指定的bean
        xStream.autodetectAnnotations(true);
        //加载指定有XStream注解的bean
        xStream.processAnnotations(o.getClass());
        return xStream.toXML(o);
    }

    /**
     * 将xml格式转化为object
     * @param c 要转化成的类
     * @param datas xml参数
     * @return 返回转化结果
     */
    public static Object toBean(Class c,String datas){
        XStream xStream=new XStream(){
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    @Override
                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        return super.shouldSerializeMember(definedIn, fieldName);
                    }
                };
            }
        };
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypes(new Class[]{Student.class,Person.class,Item.class});
        xStream.processAnnotations(new Class[]{c});
        xStream.autodetectAnnotations(true);
        return xStream.fromXML(datas);
    }

你可能感兴趣的:(部分知识,自动生成类)