zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    使用pandas的get_dummies对类目型的特征因子化
    关于RandomForestRegressor,补全null数值
    关于train_test_split和cross_val_score交叉检验
    关于seaborn
    正态分布
    单下划线或双下划线的意义
    MFC中关于运行时类信息及动态创建对象的两个宏的意义(转)
    DPDK
    根据结构体成员地址得到结构体入口地址,内核代码
    多线程频繁写全局变量导致性能降低
  • 原文地址:https://www.cnblogs.com/javallh/p/9976919.html
Copyright © 2011-2022 走看看