xml和java对象互转:JAXB注解的使用详解

时间:2020-12-01 03:25:39

先看工具类:

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;
}
}

  

二、     注解介绍

1.       Jaxb中处理java和xml之间转换的常用注解有:

1)        @XmlType

2)        @XmlElement

3)        @XmlRootElement

4)        @XmlAttribute

5)        @XmlAccessorType

6)        @XmlAccessorOrder

7)        @XmlTransient   用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素

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