Xsteam转换成JavaBean(SpringBoot遇到的问题)

public class XsteamUtil {
    public static Object toBean(Class<?> clazz, String xml) {
        Object xmlObject = null;
        XStream xstream = new XStream();
        //XStream.setupDefaultSecurity(xstream);
        //Class<?>[] classes = new Class[] { UnSubscribeV2Rsp.class, UsedCDRAuthReq.class };
        //xstream.allowTypes(classes);
        xstream.processAnnotations(clazz);
        xstream.autodetectAnnotations(true);
        //xstream.setClassLoader(UnSubscribeV2Rsp.class.getClassLoader());
        xmlObject= xstream.fromXML(xml);
        return xmlObject;
    }

}

异常 1:

Security framework of XStream not initialized, XStream is probably vulnerable.

意思是:xstream 的安全框架没有初始化,xstream 容易受攻击。

解决方法:xStream对象设置默认安全防护,同时设置允许的类

XStream.setupDefaultSecurity(xstream);
//UnSubscribeV2Rsp ,UsedCDRAuthReq (自己需要转换的JavaBean)
Class<?>[] classes = new Class[] { UnSubscribeV2Rsp.class, UsedCDRAuthReq.class };
xstream.allowTypes(classes);

异常 2: java.lang.ClassCastException: (明明类型一样,报转换异常)

在SpringBoot项目中,使用Xstream反序列化xml成实体类时,会发生明明是同种类型,在实际使用时却出现java.lang.ClassCastException的异常。

原因

因为springboot项目中不是使用的默认classloader。

解决方法

手动重设xtream的classloader

xstream.setClassLoader(UnSubscribeV2Rsp.class.getClassLoader());

加上解决问题:

public class XsteamUtil {
    public static Object toBean(Class<?> clazz, String xml) {
        Object xmlObject = null;
        XStream xstream = new XStream();
        XStream.setupDefaultSecurity(xstream);
        Class<?>[] classes = new Class[] { UnSubscribeV2Rsp.class, UsedCDRAuthReq.class };
        xstream.allowTypes(classes);
        xstream.processAnnotations(clazz);
        xstream.autodetectAnnotations(true);
        xstream.setClassLoader(UnSubscribeV2Rsp.class.getClassLoader());
        xmlObject= xstream.fromXML(xml);
        return xmlObject;
    }

}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值