public class JAXBUtils {
public static String convertToXml(Object obj, boolean format) throws Exception {
try {
StringWriter sw = new StringWriter();
Marshaller marshaller = MarshallerFactory.getMarshaller(obj.getClass());
if (marshaller == null) {
return StringUtils.EMPTY;
}
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
marshaller.marshal(obj, sw);
return sw.toString();
} catch (JAXBException e) {
throw new RuntimeException("obj toXML failed", e);
}
}
public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {
try {
Unmarshaller unmarshaller = MarshallerFactory.getUnmarshaller(t);
if (unmarshaller == null) {
return null;
}
StringReader sr = new StringReader(xml);
T ret = null;
ret = (T) unmarshaller.unmarshal(sr);
return ret;
} catch (JAXBException e) {
throw new RuntimeException("xml toObj failed", e);
}
}
}
public class MarshallerFactory {
private final static HashMap<Class, JAXBContext> JAXB_CONTEXT_MAP = Maps.newHashMap();
private MarshallerFactory() {
}
static {
try {
JAXB_CONTEXT_MAP.put(RequestBean.class, JAXBContext.newInstance(RequestBean.class));
// 想要进行的bean转换的类,可以写在这里,初始化到Map中
} catch (Exception e) {
// 打印日志
}
}
public static Marshaller getMarshaller(Class t) throws JAXBException {
Preconditions.checkNotNull(t);
JAXBContext jaxbContext = JAXB_CONTEXT_MAP.get(t);
if(jaxbContext == null) {
return null;
}
return jaxbContext.createMarshaller();
}
public static Unmarshaller getUnmarshaller(Class t) throws JAXBException {
Preconditions.checkNotNull(t);
JAXBContext jaxbContext = JAXB_CONTEXT_MAP.get(t);
if(jaxbContext == null) {
return null;
}
return jaxbContext.createUnmarshaller();
}
}
主要就是三个接口,Marshaller、UnMarchaller和JAXBContext
- JAXBContext类,是应用的入口,通过该类创建序列化和反序列化对象,也即编组对象和解组对象;
- Marshaller 编组接口,将Java对象序列化为XML数据;
- Unmarshaller 解组接口,将XML数据反序列化为Java对象。
为了便于支持多个bean的转换,可以将需要转换的类都放进Factory的静态Map中,需要用的时候直接拿出来就行了。
至于如何写bean,一种方法是手写,建议参考这篇博客https://www.cnblogs.com/chenbenbuyi/p/8283657.html
主要是弄懂各个标签的含义和作用。
另外一种方法是通过xsd文件(相当于xml的格式模板),使用IDEA的JAXB工具反向生成Java bean