赞助

JaxbUtil转json转XML工具类

json转换为XML工具类

 1 package com.cxf.value;
 2 
 3 import org.springframework.util.StringUtils;
 4 
 5 import javax.xml.bind.*;
 6 import java.io.ByteArrayOutputStream;
 7 import java.io.IOException;
 8 import java.io.StringReader;
 9 
10 import static javax.xml.bind.JAXBContext.newInstance;
11 @Sl4j
12 public class JaxbUtil {
13 
14 
15 
16     /**
17      * 对象转xml
18      * @param obj
19      * @return
20      */
21     public static String toXmlDocument(Object obj) {
22 
23         if (obj == null) {
24             return null;
25         }
26 
27         try {
28             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
29             JAXBContext context = newInstance(obj.getClass());
30             Marshaller marshaller = context.createMarshaller();
31             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
32             marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
33             marshaller.marshal(obj, byteArrayOutputStream);
34             String result = new String(byteArrayOutputStream.toByteArray());
35             if (byteArrayOutputStream != null) {
36                 byteArrayOutputStream.close();
37             }
38             return result;
39         } catch (IOException e) {
40             log.error("toXmlDocument ex.", e);
41         } catch (PropertyException e) {
42             log.error("toXmlDocument ex.", e);
43         } catch (JAXBException e) {
44             log.error("toXmlDocument ex.", e);
45         }
46 
47         return null;
48     }
49 
50     /**
51      * xml转换成JavaBean
52      * @param xml
53      * @param c
54      * @return
55      */
56     public static <T> T convertToJavaBean(String xml, Class<T> c) {
57 
58         if (StringUtils.isEmpty(xml)){
59             return null;
60         }
61         T t = null;
62         try {
63             JAXBContext context = JAXBContext.newInstance(c);
64             Unmarshaller unmarshaller = context.createUnmarshaller();
65             t = (T) unmarshaller.unmarshal(new StringReader(xml));
66         } catch (Exception e) {
67             log.error("xml to JavaBean ex.", e);
68         }
69 
70         return t;
71     }
72 }

 

posted @ 2018-11-18 02:50  念念不忘、  阅读(578)  评论(0编辑  收藏  举报