(公司项目中的工具类)xml字符串与实体互相转换工具类,银行请求接口报文xml方式
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Jaxb 工具类,使用时根据情况自己将standalone="yes"去掉
*
*/
public class JaxbUtil {
private static Logger logger = LoggerFactory.getLogger(JaxbUtil.class);
/**
* JavaBean转换成xml
*
* @param obj
* @param encoding
* @return
*/
public static String convertToXml(Object obj, String encoding, boolean format) {
String result = null;
StringWriter writer = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* xml转换成JavaBean
*
* @param xml
* @param c
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T convertToJava(String xml, Class<T> c) {
if (xml == null || xml.equals(""))
return null;
T t = null;
StringReader reader = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xml);
t = (T) unmarshaller.unmarshal(reader);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (reader != null)
reader.close();
}
return t;
}
}
@XmlElement(name="abstract")
private String abstracts; //银行提供的报文中含有abstract关键字,可以给实体属性起别名
问题记录:
银行返回的报文中,含有namespace,导致转换实体报错。改成下面这样就可以了
/**
* xml转换成JavaBean
*
* @param xml
* @param c
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T convertToJava(String xml, Class<T> c) {
if (xml == null || xml.equals(""))
return null;
T t = null;
StringReader reader = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xml);
SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false);//主要代码
XMLReader xmlReader = sax.newSAXParser().getXMLReader();
Source source = new SAXSource(xmlReader,new InputSource(reader));
t = (T) unmarshaller.unmarshal(source);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (reader != null)
reader.close();
}
return t;
}