码迷,mamicode.com
首页 > Web开发 > 详细

JaxbUtil转json转XML工具类

时间:2018-11-18 11:27:42      阅读:449      评论:0      收藏:0      [点我收藏+]

标签:byte   OLE   ade   工具类   ldo   framework   com   try   param   

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 }

 

JaxbUtil转json转XML工具类

标签:byte   OLE   ade   工具类   ldo   framework   com   try   param   

原文地址:https://www.cnblogs.com/javallh/p/9976919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!