将bean转换成XML字符串

 1 package com.sinoservices.bms.bbl.rest.bean;
 2 import javax.xml.bind.annotation.XmlAccessType;
 3 import javax.xml.bind.annotation.XmlAccessorType;
 4 import javax.xml.bind.annotation.XmlElement;
 5 import javax.xml.bind.annotation.XmlRootElement;
 6 
 7 @XmlAccessorType(XmlAccessType.FIELD)
 8 @XmlRootElement(name = "ZwbShGetCustomerCaResponse")
 9 public class BmCurrentBillResponseBean {
10     
11     @XmlElement(name = "Accountbillheader")
12     private BmCurrentBillHeaderList bmCurrentBillHeaderList;
13     @XmlElement(name = "ReturnMassage")
14     private String returnMassage;
15     @XmlElement(name = "ReturnStatus")
16     private String returnStatus;
17     
18     public BmCurrentBillHeaderList getBmCurrentBillHeaderList() {
19         return bmCurrentBillHeaderList;
20     }
21     public void setBmCurrentBillHeaderList(BmCurrentBillHeaderList bmCurrentBillHeaderList) {
22         this.bmCurrentBillHeaderList = bmCurrentBillHeaderList;
23     }
24     public String getReturnMassage() {
25         return returnMassage;
26     }
27     public void setReturnMassage(String returnMassage) {
28         this.returnMassage = returnMassage;
29     }
30     public String getReturnStatus() {
31         return returnStatus;
32     }
33     public void setReturnStatus(String returnStatus) {
34         this.returnStatus = returnStatus;
35     }
36 }

 

package com.sinoservices.bms.bch.common.util;

import java.lang.reflect.Field;
import java.util.Date;

import javax.xml.bind.Marshaller.Listener;

public class MarshallerListener extends Listener {
    public static final String BLANK_CHAR = "";

    @Override
    public void beforeMarshal(Object source) {
        super.beforeMarshal(source);
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            // 获取字段上注解<pre name="code" class="java">
            try {
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
                } else if (f.getType() == Date.class && f.get(source) == null) {
                    f.set(source, new Date());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

 

  1 package com.sinoservices.bms.bch.common.util;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.IOException;
  5 import java.io.StringReader;
  6 import java.util.regex.Matcher;
  7 import java.util.regex.Pattern;
  8 
  9 import javax.xml.bind.JAXBContext;
 10 import javax.xml.bind.JAXBException;
 11 import javax.xml.bind.Marshaller;
 12 import javax.xml.bind.Unmarshaller;
 13 
 14 import org.apache.log4j.Logger;
 15 
 16 
 17 /**
 18  * 
 19  * @Description XML工具类
 20  * @author Lynch.Feng
 21  * @Date 2018年11月30日 下午4:10:50
 22  * @version 1.0.0
 23  */
 24 public class XmlUtil {
 25     private static final Logger LOGGER = Logger.getLogger(XmlUtil.class);
 26 
 27     /**
 28      * Description:把java类解析成XML字符串
 29      * 
 30      * @param object java类
 31      * @param encoding XML编码
 32      * @return
 33      */
 34     public static String getXmlWithoutHeader(Object object) {
 35         try {
 36             JAXBContext context = JAXBContext.newInstance(object.getClass());
 37             Marshaller marshaller = context.createMarshaller();
 38             marshaller.setListener(new MarshallerListener());
 39             marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式
 40             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
 41             marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头信息
 42             ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
 43             marshaller.marshal(object, dataStream);
 44             return dataStream.toString("UTF-8");// "GBK"
 45         } catch (Exception e) {
 46             LOGGER.error("XML转换失败", e);
 47             e.printStackTrace();
 48             return "XML转换失败";
 49         }
 50     }
 51 
 52     /**
 53      * Description:把java类解析成XML字符串
 54      * 
 55      * @param object java类
 56      * @param encoding XML编码
 57      * @return
 58      */
 59     public static String getXmlFromObject(Object object, String encoding) {
 60         try {
 61             JAXBContext context = JAXBContext.newInstance(object.getClass());
 62             Marshaller marshaller = context.createMarshaller();
 63             marshaller.setListener(new MarshallerListener());
 64             marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);// 编码格式
 65             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);// 是否格式化生成的xml串
 66             marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头信息
 67             ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
 68             marshaller.marshal(object, dataStream);
 69             return dataStream.toString(encoding);// "GBK"
 70         } catch (Exception e) {
 71             LOGGER.error("XML转换失败", e);
 72             return "XML转换失败";
 73         }
 74     }
 75 
 76     /**
 77      * Description:把java类解析成XML字符串
 78      * 
 79      * @param clazz java类
 80      * @param xml XML字符串
 81      * @return
 82      */
 83     public static Object getObjectFromXml(Class<?> clazz, String xml) {
 84         try {
 85             JAXBContext context = JAXBContext.newInstance(clazz);
 86             Unmarshaller unMarshaller = context.createUnmarshaller();
 87             return unMarshaller.unmarshal(new StringReader(xml));
 88         } catch (Exception e) {
 89             LOGGER.error("XML转换失败", e);
 90             return null;
 91         }
 92     }
 93 
 94     /**
 95      * 
 96      * @Description SAP 返回结果转换为对象
 97      * @param clazz
 98      * @param xml
 99      * @param field
100      * @return
101      */
102     public static Object getSAPObject(Class<?> clazz, String xml, String field) {
103         String rgex = String.format("<%s>(.*?)</%s>", field, field);
104         try {
105             JAXBContext context = JAXBContext.newInstance(clazz);
106             Unmarshaller unMarshaller = context.createUnmarshaller();
107             Pattern pattern = Pattern.compile(rgex);
108             Matcher m = pattern.matcher(xml.replaceAll("(n0:)|(\\s?xmlns:n0)[^>]*|\r\n", ""));
109             while (m.find()) {
110                 xml = String.format("<%s>%s</%s>", field, m.group(1), field);
111             }
112             return unMarshaller.unmarshal(new StringReader(xml));
113         } catch (Exception e) {
114             LOGGER.error("XML转换失败", e);
115             return null;
116         }
117     }
118     
119     /**
120      * xml文件配置转换为对象
121      * @param xmlPath  xml文件路径
122      * @param load    java对象.Class
123      * @return    java对象
124      * @throws JAXBException    
125      * @throws IOException
126      */
127     @SuppressWarnings("unchecked")
128     public static <T> T xmlToBean(String xmlPath, Class<T> load) throws JAXBException, IOException {
129         JAXBContext context = JAXBContext.newInstance(load);
130         Unmarshaller unmarshaller = context.createUnmarshaller();
131         return (T) unmarshaller.unmarshal(new StringReader(xmlPath));
132     }
133     
134     /** 
135      * xml转换成JavaBean 
136      * @param xml 
137      * @param c 
138      * @return 
139      */
140     @SuppressWarnings("unchecked")
141     public static <T> T converyToJavaBean(String xml, Class<T> c) {
142         T t = null;
143         try {
144             JAXBContext context = JAXBContext.newInstance(c);
145             Unmarshaller unmarshaller = context.createUnmarshaller();
146             t = (T) unmarshaller.unmarshal(new StringReader(xml));
147         } catch (Exception e) {
148             e.printStackTrace();
149         }
150 
151         return t;
152     }
153     
154     
155 }

 

posted on 2019-04-10 19:34  跳舞的mundo  阅读(341)  评论(0编辑  收藏  举报

导航