xml和java對象互轉:JAXB註解的使用詳解

先看工具類:java

import org.slf4j.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mingyanliao
 * Date: 2018-11-19
 * Time: 下午2:02
 */
public class JaxbUtil {
    private final static Logger logger = getLogger(JaxbUtil.class);

    /**
     * xml轉換成JavaBean
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("XML轉Java異常.緣由:{}",e.getMessage());
        }

        return t;
    }

    /**
     * JavaBean轉換成xml去除xml聲明部分
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXmlIgnoreXmlHead(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}

  

2、     註解介紹工具

1.       Jaxb中處理java和xml之間轉換的經常使用註解有:spa

1)        @XmlType.net

2)        @XmlElementxml

3)        @XmlRootElement對象

4)        @XmlAttributeblog

5)        @XmlAccessorTypeip

6)        @XmlAccessorOrderget

7)        @XmlTransient   用於標示在由java對象映射xml時,忽略此屬性。即,在生成的xml文件中不出現此元素it

8)        @XmlJavaTypeAdapter註解使用:https://blog.csdn.net/nxdxmg/article/details/46926521

相關文章
相關標籤/搜索