You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.3 KiB
80 lines
2.3 KiB
3 years ago
|
/*
|
||
|
* Copyright (C), 2018-2021
|
||
|
* Project: starter
|
||
|
* FileName: JaxbUtil
|
||
|
* Author: xxx
|
||
|
* Date: 2021/7/22 22:26
|
||
|
*/
|
||
|
package com.fr.plugin.tabledataservice.utils;
|
||
|
|
||
|
import com.fanruan.api.log.LogKit;
|
||
|
|
||
|
import javax.xml.bind.JAXBContext;
|
||
|
import javax.xml.bind.Marshaller;
|
||
|
import javax.xml.bind.Unmarshaller;
|
||
|
import java.io.StringReader;
|
||
|
import java.io.StringWriter;
|
||
|
|
||
|
/**
|
||
|
* <Function Description><br>
|
||
|
* <JaxbUtil>
|
||
|
*
|
||
|
* @author xxx
|
||
|
* @since 1.0.0
|
||
|
*/
|
||
|
public class JaxbUtil {
|
||
|
|
||
|
public static String convertToXml(Object obj) {
|
||
|
return convertToXml(obj, "UTF-8");
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* JavaBean转换成xml
|
||
|
*
|
||
|
* @param obj
|
||
|
* @param encoding
|
||
|
* @return
|
||
|
*/
|
||
|
public static String convertToXml(Object obj, String encoding) {
|
||
|
String result = null;
|
||
|
try {
|
||
|
JAXBContext context = JAXBContext.newInstance(obj.getClass());
|
||
|
Marshaller marshaller = context.createMarshaller();
|
||
|
// xml格式
|
||
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
||
|
// 去掉生成xml的默认报文头
|
||
|
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
|
||
|
// 编码
|
||
|
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
|
||
|
// 不进行转义字符处理
|
||
|
// marshaller.setProperty(CharacterEscapeHandler.class.getName(), (CharacterEscapeHandler) (chars, start, length, isAttVal, writer) -> writer.write(chars, start, length));
|
||
|
StringWriter writer = new StringWriter();
|
||
|
marshaller.marshal(obj, writer);
|
||
|
result = writer.toString();
|
||
|
} catch (Exception ex) {
|
||
|
LogKit.error(ex.getMessage(), ex);
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* xml转换成JavaBean
|
||
|
*
|
||
|
* @param xml
|
||
|
* @param c
|
||
|
* @return
|
||
|
*/
|
||
|
@SuppressWarnings("unchecked")
|
||
|
public static <T> T converyToJavaBean(String xml, Class<T> c) {
|
||
|
T t = null;
|
||
|
try {
|
||
|
JAXBContext context = JAXBContext.newInstance(c);
|
||
|
Unmarshaller unmarshaller = context.createUnmarshaller();
|
||
|
t = (T) unmarshaller.unmarshal(new StringReader(xml));
|
||
|
} catch (Exception ex) {
|
||
|
LogKit.error(ex.getMessage(), ex);
|
||
|
}
|
||
|
return t;
|
||
|
}
|
||
|
|
||
|
}
|