分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

JaxbUtil转json转XML工具类

发布时间:2023-09-06 02:22责任编辑:蔡小小关键词:jsjson

json转换为XML工具类

 1 package com.cxf.value; 2 ?3 import org.springframework.util.StringUtils; 4 ?5 import javax.xml.bind.*; 6 import java.io.ByteArrayOutputStream; 7 import java.io.IOException; 8 import java.io.StringReader; 9 10 import static javax.xml.bind.JAXBContext.newInstance;11 @Sl4j12 public class JaxbUtil {13 14 15 16 ????/**17 ?????* 对象转xml18 ?????* @param obj19 ?????* @return20 ?????*/21 ????public static String toXmlDocument(Object obj) {22 23 ????????if (obj == null) {24 ????????????return null;25 ????????}26 27 ????????try {28 ????????????ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();29 ????????????JAXBContext context = newInstance(obj.getClass());30 ????????????Marshaller marshaller = context.createMarshaller();31 ????????????marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);32 ????????????marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");33 ????????????marshaller.marshal(obj, byteArrayOutputStream);34 ????????????String result = new String(byteArrayOutputStream.toByteArray());35 ????????????if (byteArrayOutputStream != null) {36 ????????????????byteArrayOutputStream.close();37 ????????????}38 ????????????return result;39 ????????} catch (IOException e) {40 ????????????log.error("toXmlDocument ex.", e);41 ????????} catch (PropertyException e) {42 ????????????log.error("toXmlDocument ex.", e);43 ????????} catch (JAXBException e) {44 ????????????log.error("toXmlDocument ex.", e);45 ????????}46 47 ????????return null;48 ????}49 50 ????/**51 ?????* xml转换成JavaBean52 ?????* @param xml53 ?????* @param c54 ?????* @return55 ?????*/56 ????public static <T> T convertToJavaBean(String xml, Class<T> c) {57 58 ????????if (StringUtils.isEmpty(xml)){59 ????????????return null;60 ????????}61 ????????T t = null;62 ????????try {63 ????????????JAXBContext context = JAXBContext.newInstance(c);64 ????????????Unmarshaller unmarshaller = context.createUnmarshaller();65 ????????????t = (T) unmarshaller.unmarshal(new StringReader(xml));66 ????????} catch (Exception e) {67 ????????????log.error("xml to JavaBean ex.", e);68 ????????}69 70 ????????return t;71 ????}72 }

JaxbUtil转json转XML工具类

原文地址:https://www.cnblogs.com/javallh/p/9976919.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved