xstream xml转化成java对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xstream xml转化成java对象相关的知识,希望对你有一定的参考价值。

xstream xml转化成java对象

注意事项:

    创建接收转换的实体类 里面字段 与 xml节点一一对应。spring 使用 @XStreamAlias("节点") 进行关联。属性名与节点一一对应是很重要的!!!不然 不能正常转换。使用了注解以后,xml节点跟类的属性名不再有关系,但是 注解里面使用的名字就默认是与xml节点对应的。所以保持@XStreamAlias("节点")  里面节点的值与xml 一一对应。

    xstream.processAnnotations(需要转化的实体类.class);


实体类 例子:


package com.cmsz.cmup.alipay.model.responses;


import java.util.List;


import com.thoughtworks.xstream.annotations.XStreamAlias;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import com.thoughtworks.xstream.annotations.XStreamConverter;

import com.thoughtworks.xstream.annotations.XStreamImplicit;

import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;


/**

 * @Title: AccountResultVO.java

 * @Package com.cmsz.cmup.alipay.vo.result

 * @Description: alipay返回xml字符串封装对象

 * @author yekun

 * @date 2015年12月4日 上午10:50:23

 */

@XStreamAlias("alipay")

public class AccountResponseModel


/** 错误信息 */

@XStreamAlias("error")

private String error;


/** 请求是否成功 */

@XStreamAlias("is_success")

private String isSuccess;

/** 请求参数 */

@XStreamAlias("request")

private Request request;


/** xml节点 */

@XStreamAlias("response")

private Response response;


/** 签名 */

@XStreamAlias("sign")

private String sign;


/** 签名加密方式 */

@XStreamAlias("sign_type")

private String sign_type;



//转换代码

XStream xstream = new XStream(new DomDriver());

xstream.processAnnotations(实体类.class);

xstream.fromXML(xmlStr);//xml格式的字符串

参考技术A XStream xstream = new XStream();
Object object = xstream.fromXML(xmlString);
参考技术B xml to java对象:
static MessageDatabase load(String persistFile)
MessageDatabase messageDatabase = null;
Reader reader = null;

try
reader = new FileReader(persistFile);
XStream xstream = new XStream(new JDomDriver());
messageDatabase = (MessageDatabase) xstream.fromXML(reader);

// for upgrade
if (messageDatabase != null)
messageDatabase.upgrade();


catch (FileNotFoundException ex)
;

finally
if (reader != null)
try
reader.close();

catch (IOException ex)
log.warn("Exception when closing reader", ex);




if (messageDatabase == null)
messageDatabase = new MessageDatabase();
messageDatabase.setMessages(new LinkedList());
messageDatabase.setStickyMessages(new LinkedList());


messageDatabase.persistFile = persistFile;

return messageDatabase;
参考技术C public Map<String, Object> unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context)
Map<String, Object> map = new HashMap<String,Object>();
populateMap(reader,context,map);
return map;


protected void populateMap(HierarchicalStreamReader reader,
UnmarshallingContext context, Map<String, Object> map)
while (reader.hasMoreChildren())
reader.moveDown();
String key = reader.getNodeName();
Object value = null;
if (reader.hasMoreChildren())
Map<String, Object> innerNode = new HashMap<String, Object>();
populateMap(reader, context, innerNode);
value = innerNode;
else
value = reader.getValue();

if (map.containsKey(key))
// convert to list
ArrayList<Object> list = null;
if(map.get(key) instanceof ArrayList)
list = (ArrayList<Object>)map.get(key);
else
list = new ArrayList<Object>();
list.add(map.get(key));

list.add(value);
map.put(key, list);
else
// insert into map
map.put(key, value);

reader.moveUp();
参考技术D import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XstreamTest 
public static void main(String[] args) 
//多年前用过,既然问了 我也温故知新一下
//x-stream的下载地址  http://x-stream.github.io/download.html
//将user对象转换为xml
User u = new User();
u.setAge(18);
u.setName("小明");
XStream xs = new XStream(new DomDriver());
String userXml = xs.toXML(u);
System.out.println(userXml);
//将xml转换为user对象
User user = (User) xs.fromXML("<User><name>小张</name><age>22</age></User>");
System.out.println(user.getName());
System.out.println(user.getAge());


class User 
    private String name;
    private int age;
    public int getAge() 
return age;

public void setAge(int age) 
this.age = age;

public String getName() 
            return name;
    
    public void setName(String name) 
            this.name = name;
    

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("输出成功");
    }

PS:XStream将java对象与xml之间序列化与反序列化,XStream自己封装了序列化方法,java类不用实现Serializable接口

以上是关于xstream xml转化成java对象的主要内容,如果未能解决你的问题,请参考以下文章

xstream如何将java对象转化成有cdata的xml

用XStream 转换java对象成xml的一个疑问

Java对象表示方式2:XStream实现对对象的XML化

xstream xml转化java时,节点大小写转化

XStream将XML转换为JAVA对象快速指南

关于xstream把XML转换java对象问题,求高手解答。