jaxb實現xml與bean的相互轉化

jaxb使用完整例子html

  這裏邊有提到 MessageFormat,能夠了解下。下邊還有一個其餘博客粘過來的幾行代碼,記錄一下。java

  附上幾個連接    [CXF REST標準實戰系列] 1、JAXB xml與javaBean的轉換     JAXB生成CDATA類型的節點    Jaxb如何優雅的處理CDataapache

 我這裏以《書》爲例,寫一個完整的測試代碼,xml包含了各類元素和集合。json

 test.xmlapi

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<book id="1234567890" name="尋醫不如自醫">
    <author>陳金柱</author>
    <press>金城出版社</press>
    <main_info>
        <chapters_num>5</chapters_num>
        <editor>王景濤</editor>
        <pub_time>2017-01-01</pub_time>
    </main_info>
    <chapters>
        <chapter>
            <num>1</num>
            <name>你所不知道的事</name>
        </chapter>
        <chapter>
            <num>2</num>
            <name>人體中有哪些重要的部分</name>
        </chapter>
        <chapter>
            <num>3</num>
            <name>中醫健康基礎知識</name>
        </chapter>
    </chapters>
</book>

 實體類:安全

import java.util.List;

import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * 書 * 不指定順序的時候是按英文字母排序的 * propOrder指定順序,裏邊填的是屬性的名,不是註解裏的name * 若是指定順序的話,須要把全部屬性都寫裏邊,否則會報錯 * @author changxinzhi * */ @XmlRootElement(name = "book") @XmlType(propOrder={"id","name","author","press","mainInfo","chapters"}) public class Book { private String id;//圖書ID private String name;//圖書名稱 private String author;//做者 private String press;//出版社 private MainInfo mainInfo;//重要信息 private List<Chapter> chapters;//章節信息  @XmlAttribute(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlAttribute(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name = "author") public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @XmlElement(name = "press") public String getPress() { return press; } public void setPress(String press) { this.press = press; } @XmlElement(name = "main_info") public MainInfo getMainInfo() { return mainInfo; } public void setMainInfo(MainInfo mainInfo) { this.mainInfo = mainInfo; } @XmlElementWrapper(name = "chapters") @XmlElement(name = "chapter") public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } }
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 書的重要信息
 * @author cxz
 */ @XmlRootElement(name = "main_info") public class MainInfo { private String editor;//責任編輯 private String pub_time; private String chapters_num; public String getEditor() { return editor; } public void setEditor(String editor) { this.editor = editor; } public String getPub_time() { return pub_time; } public void setPub_time(String pub_time) { this.pub_time = pub_time; } public String getChapters_num() { return chapters_num; } public void setChapters_num(String chapters_num) { this.chapters_num = chapters_num; } }
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType; /** * 章節信息 * @author cxz */ @XmlRootElement(name="chapter") @XmlType(propOrder={"num","name"}) public class Chapter { private String num; private String name; public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

工具類多線程

import java.io.StringReader;
import java.io.StringWriter; import java.text.MessageFormat; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * json使用alibaba.fastjson * @author cxz * Jaxb2.0 處理Xml與Object轉換 */ public class JaxbObjectAndXmlUtil { /** * 此處使用了Stringreader,其實Unmarshaller接口還支持 * File,InputStream,URL,StringBuffer,org.w3c.dom.Node等反序列化 * API鏈接 * http://tool.oschina.net/uploads/apidocs/jdk-zh/javax/xml/bind/Unmarshaller.html * @param xmlStr 字符串 * @param c 對象Class類型 * @return 對象實例 */ @SuppressWarnings({ "unchecked", "finally" }) public static <T> T xml2Object(String xmlStr,Class<T> c){ try{ JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr)); return t; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * 可變參數 * config裏使用佔位符 {0} {1} {2},單引號要使用兩個
* MessageFormat使用連接 * @param config * @param c * @param arguments * @return */ @SuppressWarnings("unchecked") public static <T> T xml2Object(String config,Class<T> c,Object... arguments){ try{ if (arguments.length > 0) { config = MessageFormat.format(config, arguments); } JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new StringReader(config)); return t; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * @param object 對象 * @return 返回xmlStr */ public static String object2Xml(Object object){ try{ StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshal = context.createMarshaller(); marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化輸出 marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 編碼格式,默認爲utf-8 marshal.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml頭信息 否
       

        //不進行轉移字符的處理
//        marshal.setProperty(
//          "com.sun.xml.bind.marshaller.CharacterEscapeHandler",
//          new CharacterEscapeHandler() {
//            @Override
//            public void escape(char[] ch, int start, int length,
//              boolean isAttVal, Writer writer) throws IOException {
//              writer.write(ch, start, length);
//            }
//        });app

 marshal.setProperty("jaxb.encoding", "utf-8"); marshal.marshal(object,writer); return new String(writer.getBuffer()); }catch(Exception e){ e.printStackTrace(); return null; } } }

測試類dom

import java.util.ArrayList;
import java.util.List; import com.alibaba.fastjson.JSON; public class test { /** * 測試方法 * @param args */ public static void main(String[] args){ //建立內容 MainInfo mainInfo = new MainInfo(); mainInfo.setEditor("王景濤"); mainInfo.setPub_time("2017-01-01"); mainInfo.setChapters_num("5"); Chapter chapter1 = new Chapter(); chapter1.setNum("1"); chapter1.setName("你所不知道的事"); Chapter chapter2 = new Chapter(); chapter2.setNum("2"); chapter2.setName("人體中有哪些重要的部分"); Chapter chapter3 = new Chapter(); chapter3.setNum("3"); chapter3.setName("中醫健康基礎知識"); Book book = new Book(); List<Chapter> chapters = new ArrayList<Chapter>(); chapters.add(chapter1); chapters.add(chapter2); chapters.add(chapter3); book.setChapters(chapters); book.setMainInfo(mainInfo); book.setId("1234567890"); book.setName("尋醫不如自醫"); book.setAuthor("陳金柱"); book.setPress("金城出版社"); String xmlStr = JaxbObjectAndXmlUtil.object2Xml(book);//構造報文 XML 格式的字符串 System.out.println("對象轉xml報文: \n"+xmlStr); Book book2 = JaxbObjectAndXmlUtil.xml2Object(xmlStr, Book.class); System.out.println("報文轉xml轉: \n"+JSON.toJSONString(book2)); } }

 到這裏已寫完。ide

粘過來的幾行代碼,歡迎留言討論。

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;

/**
 * 使用Jaxb2.0實現XML<->Java Object的Binder.
 * StringUtils依賴commons-long包
 * 特別支持Root對象是List的情形.---??? ‘xml規範就是有且只有一個根元素’--不甚理解這裏的作法
 * @author
 */
public class JaxbUtil {
    // 多線程安全的Context.
    private JAXBContext jaxbContext;
 
    /**
     * @param types  全部須要序列化的Root對象的類型.
     */
    public JaxbUtil(Class<?>... types) {
        try {
            jaxbContext = JAXBContext.newInstance(types);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Java Object->Xml.
     */
    public String toXml(Object root, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Java Object->Xml, 特別支持對Root Element是Collection的情形.
     */
    @SuppressWarnings("unchecked")
    public String toXml(Collection root, String rootName, String encoding) {
        try {
            CollectionWrapper wrapper = new CollectionWrapper();
            wrapper.collection = root;
 
            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(
                    new QName(rootName), CollectionWrapper.class, wrapper);
 
            StringWriter writer = new StringWriter();
            createMarshaller(encoding).marshal(wrapperElement, writer);
 
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public <T> T fromXml(String xml) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Xml->Java Object, 支持大小寫敏感或不敏感.
     */
    @SuppressWarnings("unchecked")
    public <T> T fromXml(String xml, boolean caseSensitive) {
        try {
            String fromXml = xml;
            if (!caseSensitive)
                fromXml = xml.toLowerCase();
            StringReader reader = new StringReader(fromXml);
            return (T) createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 建立Marshaller, 設定encoding(可爲Null).
     */
    public Marshaller createMarshaller(String encoding) {
        try {
            Marshaller marshaller = jaxbContext.createMarshaller();
 
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
 
            if (StringUtils.isNotBlank(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }
            return marshaller;
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 建立UnMarshaller.
     */
    public Unmarshaller createUnmarshaller() {
        try {
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 封裝Root Element 是 Collection的狀況.
* xmlAnyType查到的東西很少,不太懂這個。
*/ public static class CollectionWrapper { @SuppressWarnings("unchecked") @XmlAnyElement protected Collection collection; } }

測試方法片斷

        //寫不寫CollectionWrapper.class有什麼區別,均可以正常運行
        //將java對象轉換爲XML字符串
        JaxbUtil requestBinder = new JaxbUtil(Hotel.class,CollectionWrapper.class);
        String retXml = requestBinder.toXml(hotel, "utf-8");
        System.out.println("xml:"+retXml);
        
        //將xml字符串轉換爲java對象
        JaxbUtil resultBinder = new JaxbUtil(Hotel.class,CollectionWrapper.class);
        Hotel hotelObj = resultBinder.fromXml(retXml);
相關文章
相關標籤/搜索