/**
* xml字符串转java对象
*
* @param xmlString xml字符串
* @param clazz 要转的java对象
* @param <T> 泛型
* @return T
*/
public static <T> T xmlToBean(String xmlString, Class<T> clazz) throws XMLStreamException, JAXBException {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
XMLEventReader someSource = factory.createXMLEventReader(stream);
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<T> userElement = jaxbUnmarshaller.unmarshal(someSource, clazz);
return userElement.getValue();
}
/**
* bean对象转xml字符串
*
* @param obj bean对象
* @param clazz 要转的bean.Class
* @return object
*/
public static String beanToXml(Object obj, Class<?> clazz) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
/**
* xml字符串转Object对象
*
* @param xmlString xml字符串
* @param load 要转的bean.Class
* @return object
*/
public static Object xmlToObject(String xmlString, Class<?> load) throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance(load);
Unmarshaller unmarshaller = context.createUnmarshaller();
Object object = unmarshaller.unmarshal(new StringReader(xmlString));
return object;
}
xml和bean的转换
原创
©著作权归作者所有:来自51CTO博客作者mb650949ff24157的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:kafka常用命令
下一篇:mysql查询是否区分大小写
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java bean与xml相互转换
最近在做的项目,在各个平台之间需要大量传输数据,且结构比较复杂li * @version v1...
java c/c++ List xml