【撸码师的备忘录】 Java bean 与 xml 互相转化-JDK Marshaller

Marshaller Api :  http://www.apihome.cn/api/java/Marshaller.html

 

package lab.s2jh.core.util;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.exception.ServiceException;
import lombok.Setter;
import lombok.experimental.Accessors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

/**
 * Project :       Monster-frameWork
 * Author:         XIE-HONGFEI
 * Company:        hongfei tld.
 * Created Date:   2016/4/1 0001
 * Copyright @ 2016 Company hongfei tld. – Confidential and Proprietary
 * <p/>
 * History:
 * ------------------------------------------------------------------------------
 *      Date       |      Author     |   Change Description
 * 2016/4/1 0001   |      谢xx        |   初版做成
 *
 *  描述 :
 *  1.利用Java内置JAXB对JavaBean进行序列化为xml或将xml反序列化为java bean对象
 *  2.涉及实体Bean需有 @XmlRootElement 及 @XmlElement 注解
 *    note :
 *    @XmlElement注解只能应用在set方法中,如转换对象为ORM-Entity实体对象,则建议不再使用lombok进行代码处理;
 */

public class JaxbUtils {

    private static final Logger logger = LoggerFactory.getLogger(JaxbUtils.class);

    private JAXBContext jaxbContext;

    /**
     * 构造所有需要序列化类型的JAXBContent对象
     * @param classes
     */
    public JaxbUtils(Class<?>... classes) {
        try {
            jaxbContext = JAXBContext.newInstance(classes);
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new ServiceException("Build JAXBContext Error" + e.getMessage(), e.getCause());
        }
    }

    public String bean2Xml(Object obj) {
        try {
            //输出到控制台
            //createMarshaller().marshal(obj,System.out);

            //输出到字符流
            StringWriter writer = new StringWriter();

            createMarshaller().marshal(obj, writer);

            return writer.toString();

        } catch (JAXBException e) {
            e.printStackTrace();
            throw new ServiceException("Operate marshal error" + e.getMessage(), e.getCause());
        }
    }

    public <T> T xml2Bean(String xmlContent) {

        StringReader reader = new StringReader(xmlContent);

        try {
            return (T) createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new ServiceException("Resole xml content to bean Error" + e.getMessage(), e.getCause());
        }
    }

    /**
     * Create a <tt>Marshaller</tt> object that can be used to convert a
     * java content tree into XML data.
     *
     * @return a <tt>Marshaller</tt> object
     *
     * @throws JAXBException if an error was encountered while creating the
     *                       <tt>Marshaller</tt> object
     */
    public Marshaller createMarshaller() {
        return createMarshaller(null);
    }

    /**
     * Create a <tt>Marshaller</tt> object that can be used to convert a
     * java content tree into XML data.
     *
     * @return a <tt>Marshaller</tt> object
     *
     * @throws JAXBException if an error was encountered while creating the
     *                       <tt>Marshaller</tt> object
     */
    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 ServiceException("Create Marshaller Error , " + e.getMessage(), e.getCause());
        }

    }

    /**
     * Create an <tt>Unmarshaller</tt> object that can be used to convert XML
     * data into a java content tree.
     *
     * @return an <tt>Unmarshaller</tt> object
     *
     * @throws JAXBException if an error was encountered while creating the
     *                       <tt>Unmarshaller</tt> object
     */
    public Unmarshaller createUnmarshaller() {
        try {
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new ServiceException("Create Unmarshaller Error," + e.getMessage(), e.getCause());
        }
    }

    /**
     * @author Administrator
     *
     */
    @Setter
    @Accessors(chain = true)
    @XmlRootElement(name = "example")
    static class Example {

        private String examId;

        //针对实体属性与xml节点名称不一致的情况,可采用name指定的方式进行映射;

        private String examName;

        private List<ExampleChild> childs;

        @Override
        public String toString() {
            return "no:" + examId + "\n" + "name:" + examName;
        }

        @XmlElement
        public String getExamId() {
            return examId;
        }

        @XmlElement(name = "example_name")
        public String getExamName() {
            return examName;
        }

        //节点外层包裹 example_childs层
        @XmlElementWrapper(name = "example_childs")
        @XmlElement(name = "example_child")
        public List<ExampleChild> getChilds() {
            return childs;
        }

    }

    /**
     * 
     * XmlElement作用于getter
     * @author Administrator
     *
     */
    @Setter
    static class ExampleChild {

        @MetaData(value = "子节点编号")
        private String childNo;

        @MetaData(value = "子节点名称")
        private String childName;

        @XmlElement
        public String getChildNo() {
            return childNo;
        }

        @XmlElement
        public String getChildName() {
            return childName;
        }

    }

    public static void main(String[] args) {

        JaxbUtils jaxbUtils = new JaxbUtils(Example.class);

        Example example = new Example();

        example.setExamId("10086");
        example.setExamName("中国移动示例");

        List<ExampleChild> childs = Lists.newArrayList();
        example.setChilds(childs);
        for (int i = 0; i < 3; i++) {
            ExampleChild child = new ExampleChild();
            child.setChildNo((i + 1) + "");
            child.setChildName("子节点名称-" + i);
            childs.add(child);
        }

        System.out.println("=========================  bean2Xml 结果开始  =============================");
        System.out.println(jaxbUtils.bean2Xml(example));
        System.out.println("=========================  bean2Xml 结果结束  =============================");


        String xmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<example>\n" + "    <examId>10010</examId>\n"
                + "    <example_name>中国联通示例</example_name>\n" + "</example>";

        Example example2 = jaxbUtils.xml2Bean(xmlContent);

        System.out.println("=========================  xml2Bean 结果开始  =============================");
        System.out.println(JsonUtils.writeValueAsString(example2));
        System.out.println("=========================  xml2Bean 结果开始  =============================");
    }

}

 

 

输出内容:

 

=========================  bean2Xml 结果开始  =============================
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<example>
    <example_childs>
        <example_child>
            <childName>子节点名称-0</childName>
            <childNo>1</childNo>
        </example_child>
        <example_child>
            <childName>子节点名称-1</childName>
            <childNo>2</childNo>
        </example_child>
        <example_child>
            <childName>子节点名称-2</childName>
            <childNo>3</childNo>
        </example_child>
    </example_childs>
    <examId>10086</examId>
    <example_name>中国移动示例</example_name>
</example>

=========================  bean2Xml 结果结束  =============================



=========================  xml2Bean 结果开始  =============================
{"examId":"10010","examName":"中国联通示例","childs":null}
=========================  xml2Bean 结果开始  =============================

 

 

 

 

转载于:https://my.oschina.net/xiehongfei/blog/651294

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值