加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML格式String 与 Object互换

发布时间:2020-12-16 06:22:23 所属栏目:百科 来源:网络整理
导读:最近项目用到xml格式的String类型与Object类型的相互转换,经过学习和前辈指点终于有所了解。在此写两个方法用户相互转换: 1、Object转化为xml格式String public static String toXml(Object obj) {String xmlStr = null;JAXBContext jaxbContext = null;Ma

最近项目用到xml格式的String类型与Object类型的相互转换,经过学习和前辈指点终于有所了解。在此写两个方法用户相互转换:

1、Object转化为xml格式String

public static String toXml(Object obj) {
		String xmlStr = null;
		JAXBContext jaxbContext = null;
		Marshaller marshaller = null;
		StringWriter writer = null;
		try {
			jaxbContext = JAXBContext.newInstance(obj.getClass());
			marshaller = jaxbContext.createMarshaller();
			writer = new StringWriter();
			marshaller.marshal(obj,writer);
			xmlStr = writer.toString();
		} catch (JAXBException e) {
			LOGGER.error("转换失败");
		}
		return xmlStr;
	}

2、xml格式String转化为Object
public static <T> T fromXml(String xmlStr,Class<T> _class) {
		T result = null;
		JAXBContext jaxbContext = null;
		try {
			StringReader reader = new StringReader(xmlStr);
			jaxbContext = JAXBContext.newInstance(_class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			result = (T) jaxbUnmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读