最近项目用到xml格式的String类型与Object类型的相互转换,经过学习和前辈指点终于有所了解。在此写两个方法用户相互转换:
1、Object转化为xml格式String
public static String toXml(Object obj) {
String xmlStr = null;
JAXBContext jaxbContext = null;
Marshaller marshaller = null;
StringWriter writer = null;
try {
jaxbContext = JAXBContext.newInstance(obj.getClass());
marshaller = jaxbContext.createMarshaller();
writer = new StringWriter();
marshaller.marshal(obj, writer);
xmlStr = writer.toString();
} catch (JAXBException e) {
LOGGER.error("转换失败");
}
return xmlStr;
}
2、xml格式String转化为Object
public static <T> T fromXml(String xmlStr, Class<T> _class) {
T result = null;
JAXBContext jaxbContext = null;
try {
StringReader reader = new StringReader(xmlStr);
jaxbContext = JAXBContext.newInstance(_class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
result = (T) jaxbUnmarshaller.unmarshal(reader);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}