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

用 Jaxb 对 XML 和 JavaBean相互转换

发布时间:2020-12-16 09:38:46 所属栏目:百科 来源:网络整理
导读:用ConcurrentMap 对JAXBContext进行缓存,提高效率。 private static ConcurrentMapClass?,JAXBContext jaxbContexts = new ConcurrentHashMapClass?,JAXBContext();/** * 把xml转换成对应的bean * * @param T * @param clazz * @param xml * @return */publ

用ConcurrentMap 对JAXBContext进行缓存,提高效率。


private static ConcurrentMap<Class<?>,JAXBContext> jaxbContexts = new ConcurrentHashMap<Class<?>,JAXBContext>();

	/**
	 * 把xml转换成对应的bean
	 * 
	 * @param <T>
	 * @param clazz
	 * @param xml
	 * @return
	 */
	public static <T> T parseXml2Bean(Class<T> clazz,String xml) {
		if (StringUtils.isBlank(xml)) {
			return null;
		}
		try {
			StringReader reader = new StringReader(xml);
			return clazz.cast(createUnmarshaller(clazz).unmarshal(reader));
		} catch (JAXBException e) {
			throw new RuntimeException("Could not parse xml to class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 把bean转换成对应的xml
	 * 
	 * @param obj
	 * @return
	 */
	public static String parseBean2Xml(Object obj) {
		return parseBean2Xml(obj,null,false);
	}

	/**
	 * 是否省略xml头信息
	 * 
	 * @param obj
	 * @param encoding
	 *            编码格式
	 * @param bool
	 *            是否省略xml头信息
	 * @return
	 */
	public static String parseBean2Xml(Object obj,String encoding,boolean bool) {
		if (obj == null) {
			return null;
		}
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			createMarshaller(obj.getClass(),encoding,bool).marshal(obj,os);
			return os.toString("UTF-8");
		} catch (JAXBException e) {
			throw new RuntimeException("Could not parse [" + obj + "] to xml " + e.getMessage(),e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}

	/**
	 * 创建Marshaller并设定encoding(可为null). <br/>
	 * 线程不安全,需要每次创建或pooling。
	 */
	private static Marshaller createMarshaller(Class<?> clazz,boolean bool) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);// 是否格式化生成的xml串
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT,bool);// 是否省略xml头信息
			if (StringUtils.isNotBlank(encoding)) {
				marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);
			}
			return marshaller;
		} catch (JAXBException e) {
			throw new RuntimeException("Could not createMarshaller for class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 创建UnMarshaller. <br/>
	 * 线程不安全,需要每次创建或pooling。
	 */
	private static Unmarshaller createUnmarshaller(Class<?> clazz) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			return jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			throw new RuntimeException("Could not createUnmarshaller for class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 维护jaxbContexts
	 */
	private static JAXBContext getJaxbContext(Class<?> clazz) {
		Validate.notNull(clazz,"'clazz' must not be null");
		JAXBContext jaxbContext = jaxbContexts.get(clazz);
		try {
			if (jaxbContext == null) {
				jaxbContext = JAXBContext.newInstance(clazz);
				JAXBContext j = jaxbContexts.putIfAbsent(clazz,jaxbContext);
				if (j != null) {
					jaxbContext = j;
				}
			}
		} catch (JAXBException e) {
			throw new RuntimeException(
					"Could not instantiate JAXBContext for class [" + clazz + "]: " + e.getMessage(),e);
		}
		return jaxbContext;
	}

(编辑:李大同)

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

    推荐文章
      热点阅读