在處理移動MMarket支付的時候,發現相關的類裏使用了:@XmlRootElement 的註解·
搜索了一下,才知道JAXB:JAXB(Java Architecture for XML Binding) 是一個業界的標準,是一項可以根據XML Schema產生Java類的技術
以下是互轉的一些方法代碼:
/**
* 將JAVA對象轉爲XML對象輸出:注意:需使用jaXB的註解
* @return
* @throws JAXBException
*/
public static String java2XML(Object obj) throws JAXBException{
JAXBContext context =JAXBContext.newInstance(obj.getClass());
Marshaller mar = context.createMarshaller();
mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter writer = new StringWriter();
mar.marshal(obj, writer);
return writer.toString();
}
/**
* xml轉換爲java對象
* @param xml
* @param c
* @return
* @throws JAXBException
*/
@SuppressWarnings("unchecked")
public static <T> T xml2Java(String xml, Class<T> c) throws JAXBException {
T t = null;
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
return t;
}