XStream将JavaBean转为xml

在项目中突然要想使用xml ,又涉及到java对象转为xml ,于是就学习了XStream,并封装了Xml工具类,于是就编写本博客作为记录。

具体使用可以看这篇文章: XStream 简介

不多说,直接上代码 ,如下所示:

 javabean代码如下:

@XStreamAlias("bank")
public class Bank {
    private String name;

    private String address;

    private Map map;

    private List accounts;
//省略 setter 和getter
}

封装工具类如下:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class XmlUtils {
    public static Boolean useConverter = true; // 是否使用map转换器。
    private static Converter converter = new MapEntryConverter(); //转换器

    public static Converter getConverter() {
        return converter;
    }

    private static  XStream getXStream(Class t) {
        //创建解析XML对象
        XStream xStream = new XStream(new DomDriver());
        //处理注解
        xStream.processAnnotations(t);
        if (useConverter)
            xStream.registerConverter(converter);
        return xStream;
    }

    /**
     * XML转对象
     *
     * @param clazz 对象类
     * @param xml   xml字符串
     * @param    T
     * @return
     */
    public static  T parseFromXml(Class clazz, String xml) {
        XStream xStream = getXStream(clazz);
        @SuppressWarnings("unchecked")
        T t = (T) xStream.fromXML(xml);//将XML字符串转为bean对象
        return t;
    }

    /**
     * 对象转xml
     *
     * @param obj 对象
     * @return
     */
    public static String toXml(Object obj) {
        XStream xStream = getXStream(obj.getClass());
        return xStream.toXML(obj);
    }

    private static class MapEntryConverter implements Converter {
        public boolean canConvert(Class clazz) {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                writer.startNode(entry.getKey().toString());
                writer.setValue(entry.getValue().toString());
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Map map = new HashMap();
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                map.put(reader.getNodeName(), reader.getValue());
                reader.moveUp();
            }
            return map;
        }
    }
}

考虑到项目中的javaBean中也可能存在map集合,于是我在工具类上又自定义了一个转换器,用于对map集合进行处理。

 

测试代码如下:

   private static void test2() {
//        XmlUtils.useConverter = true;
        Bank bank = getBank();

        String result = XmlUtils.toXml(bank);
        System.out.println(result);

        System.out.println("-------------------转换结束-------");
        Bank newBank = XmlUtils.parseFromXml(Bank.class, result);

        System.out.println(newBank);

    }
private static Bank getBank() {
        Bank bank = new Bank();
        Account account1 = new Account();
        Account account2 = new Account();
        account1.setAccoutId(1);
        account1.setAccountName("aaa");
        account1.setAccountMoeny(100);
        account1.setTelNum("1333333333");

        account2.setAccoutId(2);
        account2.setAccountName("sunli");
        account2.setAccountMoeny(200);
        account2.setTelNum("14444444");

        List accounts = new ArrayList();
        accounts.add(account1);
        accounts.add(account2);

        Map map = new HashMap<>();
        map.put("test", "111");
        map.put("test2", "1001");
        map.put("test3", "000");
        bank.setMap(map);
        bank.setName("中国人民银行");
        bank.setAddress("地球");
        bank.setAccounts(accounts);

        return bank;
    }

控制台输出如下:

XStream将JavaBean转为xml_第1张图片

请注意看, 打印出的xml 中的map节点,如果使用XStream默认的转换器打印出来的map下的节点数据并不是这样。

你可能感兴趣的:(java)