XStream--java对象与xml形式文件相互转换
1.pom.xml中添加依赖
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency>
2.创建xmlUtil类,并对XStream配置
2.1 解决双下划线:XStream把对象中的属性如person_name转成xml格式时会出现<person__name>,这种双下划线
此时用这种方式可以将双下划线代替成单下划线
//解决双下划线 public static final XmlFriendlyNameCoder nameCoder = new XmlFriendlyNameCoder("-_", "_");
2.2 编码格式:
// 编码格式 private static final String ENCODING = "UTF-8";
2.3 使用dom解析方式
// dom解析驱动 private static final DomDriver fixDriver = new DomDriver(ENCODING, nameCoder);
2.4 通用解析器,把配置都放到XStream对象中
// 通用解析器 public static final XStream XSTREAM = new XStream(fixDriver);
2.5 对象中有日期注意时区处理
//时区 private static final String CHINA_TIME_ZONE = "Asia/Shanghai";
2.6 初始化XStream
static { // 时区处理 TimeZone zone = TimeZone.getTimeZone(CHINA_TIME_ZONE); //获得时区 XSTREAM.registerConverter(new DateConverter(zone), XStream.PRIORITY_NORMAL); XSTREAM.autodetectAnnotations(true); //开启序列化的注解形式 XSTREAM.setMode(XStream.NO_REFERENCES);//取消引用,如果没有这一步,会出现xml引用格式reference }
3. XStream的方法
3.1 报文转对象
public static Object fromXML(String xml) { Object target = null; XStream xstream = XSTREAM; xstream.processAnnotations(AllCase.class);//开启此类的解析,否则无法解析 try { target = xstream.fromXML(xml); } catch (Exception e) { e.printStackTrace(); } return target; }
3.2 对象转报文
public static String toXML(Object obj) { XStream xstream = XSTREAM; String xml= xstream.toXML(obj); return xml; }
3.3 文件流转对象
public static Object fromXML(InputStream in) { Object target = null; XStream xstream = XSTREAM; xstream.processAnnotations(AllCase.class); try { target = xstream.fromXML(in); System.out.println("输入成功"); } catch (Exception e) { e.printStackTrace(); } return target; }
3.4对象转文件流
public static void toXML(Object obj, OutputStream out) { XStream xstream = XSTREAM; xstream.toXML(obj,out); System.out.println("输出成功"); }