通过JAXB将对象与XML相互转换
JAXB是一个非常通用的工业标准,它可以对一个实体类进行配置,指定该对象与XML或JSON格式数据的转换映射。本文将介绍如何不借助第三方工具,直接将Java Object与XML文档进行双向转换的操作。关于JSON格式的转换以及JAXB注解配置的使用,暂不做讨论,将后续再写文章进行整理。 package com.tech4j.demo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private Integer age;
// 省略 Getter Setter
}
非常简单,其中只有一个注解 package com.tech4j.demo;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private Integer age;
@XmlElement(name = "XingMing")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
下面这个工具类提供了 package com.tech4j.demo;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JaxbUtil {
@SuppressWarnings("unchecked")
public synchronized static <T> T fromXml(String xmlStr,Class<T> _class) {
T result = null;
try {
StringReader reader = new StringReader(xmlStr);
JAXBContext context = JAXBContext.newInstance(_class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Object obj = unmarshaller.unmarshal(reader);
if (!_class.isAssignableFrom(obj.getClass())) {
throw new RuntimeException("转换得到的对象并非指定类型范围内的对象!");
}
result = (T) obj;
reader.close();
} catch (JAXBException | RuntimeException e) {
e.printStackTrace();
}
return result;
}
public synchronized static String toXml(Object obj) {
String xmlStr = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(obj,writer);
xmlStr = writer.toString();
writer.close();
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
return xmlStr;
}
}
需要注意其中 com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
类的两个属性具有相同名称 "name"
this problem is related to the following location:
at public java.lang.String com.tech4j.demo.Person.getName()
at com.tech4j.demo.Person
this problem is related to the following location:
at private java.lang.String com.tech4j.demo.Person.name
at com.tech4j.demo.Person
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |