XML和Java对象互转实现(XStream方式)

1、引入Maven依赖


<dependency>  
 <groupId>com.thoughtworks.xstream</groupId>  
 <artifactId>xstream</artifactId>  
 <version>1.4.18</version>  
</dependency>

2、测试代码

2.1 基础类

package com.MyModel;  
  
public class MyBeanXStreamXml {  
  
 private String name;  
    private String id;  
    private String age;  
  
    public String getName() {  
 return name;  
    }  
  
 public void setName(String name) {  
 this.name = name;  
    }  
  
 public String getId() {  
 return id;  
    }  
  
 public void setId(String id) {  
 this.id = id;  
    }  
  
 public String getAge() {  
 return age;  
    }  
  
 public void setAge(String age) {  
 this.age = age;  
    }  
}

2.2 测试代码


package com.TestArch;  
  
import com.MyModel.MyBeanXStreamXml;  
import com.alibaba.fastjson.JSON;  
import com.thoughtworks.xstream.XStream;  
import com.thoughtworks.xstream.security.AnyTypePermission;  
import lombok.SneakyThrows;  
  
public class TestXMLByXStream {  
 @SneakyThrows  
 public static void main(String args[]) {  
 MyBeanXStreamXml myBeanXml = new MyBeanXStreamXml();  
        myBeanXml.setAge("28");  
        myBeanXml.setId("01");  
        myBeanXml.setName("PHC");  
        // 对象转 XML System.out.println("----------对象转 XML-------------------");  
        XStream xStream = new XStream();  
        String xml = xStream.toXML(myBeanXml);  
        System.out.println(xml);  
  
        System.out.println("----------对象转 XML:修改根节点标识-------------------");  
        xStream.alias("ROOT", MyBeanXStreamXml.class);  // 修改根节点标识  
 String xml2 = xStream.toXML(myBeanXml);  
        System.out.println(xml2);  
  
        System.out.println("----------XML 字符串转对象-------------------");  
        XStream xStreamForStr = new XStream();  
        xStreamForStr.addPermission(AnyTypePermission.ANY); //没有这行会报错:com.thoughtworks.xstream.security.ForbiddenClassException  
 MyBeanXStreamXml person2 = (MyBeanXStreamXml) xStreamForStr.fromXML(xml);  
        System.out.println("" + JSON.toJSONString(person2));  
    }  
}

3、测试代码输出

4、GitHub代码提交记录:

1、XML和对象的相关转换(XStream方式); · NullTommy/hello@537337d

5、参考

[参考: xstream异常com.thoughtworks.xstream.security.ForbiddenClassException_夜空中最亮的开心颜7的博客-CSDN博客 https://blog.csdn.net/weixin_42228939/article/details/95890201 ]
[参考: XStream使用详解 - 技术江湖-小焕 - 博客园 https://www.cnblogs.com/LiZhiW/p/4313493.html ]
[参考: XStream的简单使用_小异常的博客-CSDN博客 https://blog.csdn.net/sun8112133/article/details/90482307 ]

posted @ 2022-01-17 16:01  不无聊  阅读(912)  评论(0编辑  收藏  举报