当前位置: 代码迷 >> 综合 >> SpringBoot环境下 XStream XML与Bean 相互转换
  详细解决方案

SpringBoot环境下 XStream XML与Bean 相互转换

热度:11   发布时间:2023-12-15 02:47:32.0

SpringBoot环境下,XML转对象时,同一个类无法进行转换,原因是因为SpringBoot重新加载了对象;若未指定classloader的时候,SpringBoot未正确使用classloader,需要指定classloader,需要在方法中指定加载的类,添加如下代码:
xstream.setClassLoader(clazz.getClassLoader());

如:

public static <T> T toBean(Class<T> clazz, String xml) {
    try {
    XStream xstream = new XStream();xstream.processAnnotations(clazz);xstream.autodetectAnnotations(true);return (T) xstream.fromXML(xml);} catch (Exception e) {
    log.error("[XStream]XML转对象出错:{}", e.getCause());throw new RuntimeException("[XStream]XML转对象出错");}
}

更改为:

public static <T> T toBean(Class<T> clazz, String xml) {
    try {
    XStream xstream = new XStream();xstream.processAnnotations(clazz);xstream.autodetectAnnotations(true);xstream.setClassLoader(clazz.getClassLoader());return (T) xstream.fromXML(xml);} catch (Exception e) {
    log.error("[XStream]XML转对象出错:{}", e.getCause());throw new RuntimeException("[XStream]XML转对象出错");}}
  相关解决方案