import com.aaa.WorkWeixinEncrypt; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; public class XmlToObjUtil { /** * Object转xml * JAXB 是jdk 自带的工具,jdk1.6已经集成,1.5之前的版本需要另外导包 * @param object * @return * @throws JAXBException */ public String object2xml(Object object) throws JAXBException { StringWriter stringWriter = new StringWriter(); JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(object, stringWriter); return new String(stringWriter.getBuffer()); } /** * xml转Object * @param str * @param clazz * @param <T> * @return * @throws JAXBException */ public <T> T xml2Object(String str, Class<T> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); return (T)unmarshaller.unmarshal(new StringReader(str)); } public static void main(String[] args)throws Exception { String str = "<xml>" + " <toUserName>aaa</toUserName>\n" + " <fromUserName> <![CDATA[sys]]></fromUserName>\n" + "</xml>"; WorkWeixinEncrypt aa = new XmlToObjUtil().xml2Object(str, WorkWeixinEncrypt.class); System.err.println(); } }
import lombok.Data; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @Data @XmlRootElement(name="xml")//这个注解需要 public class WorkWeixinEncrypt implements Serializable {private String toUserName; private String fromUserName; }
标签:xml,java,xml2Obj,JAXBException,marshaller,import,javax,String From: https://www.cnblogs.com/xiaoliu66007/p/17041012.html