package com.gk.firework.Domain.Utils; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; import java.io.StringWriter; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by Administrator on 2017/11/29. */ public class JaxbUtils { public static String JaxbObj2Xml (Object object,Boolean withhead){ String xmlString=""; try { StringWriter sw = new StringWriter(); Marshaller jaxbMarshaller = null; try { JAXBContext jaxbContext = getContext(object.getClass()); jaxbMarshaller = jaxbContext.createMarshaller(); } catch (JAXBException e) { e.printStackTrace(); } jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); // 格式化输出 jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式,默认为utf-8 jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头信息 jaxbMarshaller.marshal(object, sw); xmlString=sw.toString(); if(withhead) { xmlString = "" + xmlString; } } catch (JAXBException e) { e.printStackTrace(); } return xmlString; } public static T JaxbXml2Obj(String xmlstr, Class classz) throws JAXBException { T req; try { JAXBContext context = JAXBContext.newInstance(classz); Unmarshaller shaller = context.createUnmarshaller(); req = (T) shaller.unmarshal(new StringReader(xmlstr)); } catch (JAXBException e) { throw e; } return req; } public static Map,JAXBContext> contextMap = new ConcurrentHashMap,JAXBContext>(); public static String convertToXml(Object obj) throws JAXBException{ Class clazz; if (obj instanceof JAXBElement){ clazz = ((JAXBElement)obj).getDeclaredType(); }else { clazz = obj.getClass(); } StringWriter sw = new StringWriter(); getContext(clazz).createMarshaller().marshal(obj,sw); return sw.toString(); } public static T convertToJavaBean(String xml,Classclazz)throws JAXBException{ StringReader reader = new StringReader(xml); return getContext(clazz).createUnmarshaller().unmarshal(new StreamSource(reader),clazz).getValue(); } private static JAXBContext getContext(Classclazz) throws JAXBException{ JAXBContext context = contextMap.get(clazz); if (null == context){ context = JAXBContext.newInstance(clazz); contextMap.put(clazz,context); } return context; } }