当前位置: 代码迷 >> 综合 >> Xsteam转换成JavaBean(SpringBoot遇到的问题)
  详细解决方案

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

热度:26   发布时间:2023-10-17 06:41:10.0
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;}}

 

 

  相关解决方案