美文网首页
JAVA复杂对像与XML互转,支持集合等复杂属性

JAVA复杂对像与XML互转,支持集合等复杂属性

作者: TryCatch菌 | 来源:发表于2019-06-13 16:21 被阅读0次

    使用的javax这个jar下的类,JAXB(Java Architecture for XML Binding) 这个java和xml的互转标准如果感兴趣可以自行百度这里就不介绍概念,直接上代码。


    首先是工具类,这里比较简单,就没做生成实体文件,就是两个,一个对像转xml,一个xml转对像。

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @desc: xml 工具类
     * @author: wangzhh
     * @date: 2019-06-13
     */
    public class XmlUtils {
    
        /**
         * Description bean对像转换为xml字符串,
         * 对像属性如果不设置值,xml字符串没有节点,如果需要空节点,可以设置为空字符串
         * @param obj 需要转换的对像,转换的对像需要做对应的注解
         * @return java.lang.String
         * @Author wangzhh
         * @Date 2019-06-13
         **/
        public static String convertToXml(Object obj) {
            // 输出流
            StringWriter writer = new StringWriter();
            try {
                JAXBContext context = JAXBContext.newInstance(obj.getClass());
                Marshaller marshaller = context.createMarshaller();
                // 格式化xml输出的格式
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                //marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
                // 设置编码集
                marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
                // 将对象转换成输出流形式的xml
                marshaller.marshal(obj, writer);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return writer.toString();
        }
    
        /**
         * Description xml字符串转换为bean对像
         * @Author wangzhh
         * @Date 2019-06-13
         * @param clazz
         * @param xmlStr
         * @return java.lang.Object
         **/
        public static Object convertXmlStrToObject(Class clazz, String xmlStr) {
    
            Object xmlObject = null;
            try {
                JAXBContext context = JAXBContext.newInstance(clazz);
                // 进行将Xml转成对象
                Unmarshaller unmarshaller = context.createUnmarshaller();
                StringReader reader = new StringReader(xmlStr);
                xmlObject = unmarshaller.unmarshal(reader);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return xmlObject;
        }
    
        public static void main(String[] args) {
            TestXmlBean t = new TestXmlBean();
            t.setName("张三");
            t.setAge("");
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("map","mapValue");
            t.setMsgMap(map);
            List<TestListBean> listBean = new ArrayList<TestListBean>();
            TestListBean t1 = new TestListBean();
            t1.setAddress("一号地址");
            TestListBean t2 = new TestListBean();
            t2.setAddress("二号地址");
            listBean.add(t1);
            listBean.add(t2);
            t.setListBean(listBean);
            System.out.println(XmlUtils.convertToXml(t));
            String xmlStr  = XmlUtils.convertToXml(t);
            xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?><test><name>张三</name><age></age><msgMap><entry><key>map</key><value>mapValue</value></entry></msgMap><listBean><address>一号地址</address></listBean><listBean><address>二号地址</address></listBean></test>\n";
            TestXmlBean bean = (TestXmlBean) XmlUtils.convertXmlStrToObject(TestXmlBean.class,xmlStr);
            System.out.println(bean.toString());
        }
    }
    
    

    测试用的类,饱含集合

    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    import java.io.Serializable;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @desc: 工具类测试对像
     * @author: wangzhh
     * @date: 2019-06-13
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    // 根节点
    @XmlRootElement(name = "test")
    // 需要转换的属性,顺序
    @XmlType(propOrder = {"name","age","msgMap","listBean"})
    public class TestXmlBean implements Serializable {
    
        private static final long serialVersionUID = -6854694430588003755L;
    
        private  String name;
        private String age;
        private Map<String,Object> msgMap;
        private List<TestListBean> listBean;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public Map<String, Object> getMsgMap() {
            return msgMap;
        }
    
        public void setMsgMap(Map<String, Object> msgMap) {
            this.msgMap = msgMap;
        }
    
        public List<TestListBean> getListBean() {
            return listBean;
        }
    
        public void setListBean(List<TestListBean> listBean) {
            this.listBean = listBean;
        }
    
        @Override
        public String toString() {
            return "TestXmlBean{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    ", msgMap=" + msgMap +
                    ", listBean=" + listBean +
                    '}';
        }
    }
    
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    
    /**
     * @desc:
     * @author: wangzhh
     * @date: 2019-06-13
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    // 根节点
    @XmlRootElement(name = "listBean")
    // 需要转换的属性
    @XmlType(propOrder = {"address"})
    public class TestListBean {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "TestListBean{" +
                    "address='" + address + '\'' +
                    '}';
        }
    }
    
    

    测试结果,控制台成功输出

    Connected to the target VM, address: '127.0.0.1:49443', transport: 'socket'
    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <test>
        <name>张三</name>
        <age></age>
        <msgMap>
            <entry>
                <key>map</key>
                <value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">mapValue</value>
            </entry>
        </msgMap>
        <listBean>
            <address>一号地址</address>
        </listBean>
        <listBean>
            <address>二号地址</address>
        </listBean>
    </test>
    
    TestXmlBean{name='张三', age='', msgMap={map=[value: null]}, listBean=[TestListBean{address='一号地址'}, TestListBean{address='二号地址'}]}
    

    相关文章

      网友评论

          本文标题:JAVA复杂对像与XML互转,支持集合等复杂属性

          本文链接:https://www.haomeiwen.com/subject/mibsfctx.html