xml2Obj,xml转java对象

 

 

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;

}

 

posted @ 2023-01-10 17:55  君子笑而不语  阅读(132)  评论(0编辑  收藏  举报