JAXB实现对象与xml互转
import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class XmlUtil { /** * JAVA对象转xml * @param object java对象 * @param <T> * @return xml字符串 * @throws JAXBException */ public static <T> String convertXml(T object) throws JAXBException { JAXBContext context = JAXBContext.newInstance(object.getClass()); // 创建 Marshaller装配器实例 Marshaller marshaller = context.createMarshaller(); // 可以设置的属性参见方法:com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty() marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name()); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // 指定xml文件头 marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 将xml写入流中 marshaller.marshal(object, outputStream); // 将流转换成字符串 return new String(outputStream.toByteArray(), StandardCharsets.UTF_8); } /** * xml报文转java对象 * @param xml xml报文 * @param clazz java对象类 * @param <E> * @return java对象 * @throws JAXBException */ public static <E> E convertObject(String xml, Class<E> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); // 创建unmarshaller解组器实例 Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader stringReader = new StringReader(xml); return (E) unmarshaller.unmarshal(stringReader); } /** * xml文件流转java对象 * @param inputStream xml文件流 * @param clazz java对象类型 * @param <E> * @return java对象 * @throws JAXBException */ public static <E> E convertObject(InputStream inputStream, Class<E> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); // 创建unmarshaller解组器实例 Unmarshaller unmarshaller = context.createUnmarshaller(); return (E) unmarshaller.unmarshal(inputStream); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2018-10-18 基于swagger进行接口文档的编写