JAXB实现xml与bean之间的转换

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值