XML与各种格式的数据进行转换的工具类

1、使用场景

一般使用的场景是与c++服务器端进行通信时,需要将对象转换为xml字符串,然后将xml字符串的数据加上指令码一起发送到服务器进行相关操作。

代码伸缩:

 @Override
    public void cleanRoomUser(RoomOperateDto roomOperateDto) {
        // 验证会议室ID存不存在
        checkRoomExist(roomOperateDto.getRoomId());
        // 请求xml
        String operator = StringUtils.isBlank(roomOperateDto.getOperator()) ? "" : roomOperateDto.getOperator();
        String appBackNotify
                = StringUtils.isBlank(roomOperateDto.getAppBackNotify()) ? "" : roomOperateDto.getAppBackNotify();
        roomOperateDto.setOperator(new String(operator.getBytes(), StandardCharsets.UTF_8));
        roomOperateDto.setAppBackNotify(
                new String(appBackNotify.getBytes(), StandardCharsets.UTF_8));
        ReqCleanRoomUsersBean request =
                new ReqCleanRoomUsersBean(roomOperateDto.getRoomId(),
                        roomOperateDto.getOperator(), roomOperateDto.getAppBackNotify());
        String requestContent = ResponseXmlUtil.responseToNoHeadXml(request);

        // 与服务器建立连接,并发送消息
        NettyClient client = null;
        try {
            client = fmapiBean.getNettyClient();
            //重点是这个方法
            Response res = client.sent(NettyConstant.MODULE1, NettyConstant.COMMAND13, requestContent);
            String content = new String(res.getContent(), StandardCharsets.UTF_8);
            ResponseDefeatBean responseDefeatBean = ResponseXmlUtil.xml2Bean(content, ResponseDefeatBean.class);
            if (!SystemConst.SUCCESS.equals(responseDefeatBean.getCode())) {
                throw new ServiceException(responseDefeatBean.getCode(), responseDefeatBean.getMsg());
            }
        } catch (ServiceException ex) {
            throw new ServiceException(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            throw new ServiceException(SystemConst.UNABLE_CONNECT_SERVER, "无法连接会议服务器");
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

这里具体方法每个人都不一样,关注即可,重点是下面的工具类,方便后面开发使用。

2、上工具类

/*
 * Project Name:fmapi
 * File Name:ResponseXmlUtil.java
 * Package Name:com.hst.ces.utils
 * Date:2016年5月5日
 * Copyright (c) 2016 HST Inc. All Rights Reserved.
 *
 */

package com.hst.ces.fmapirest.utils;

import com.hst.ces.fmapirest.entity.responsebean.ResponseDefeatBean;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author Solin
 */
@Slf4j
public class ResponseXmlUtil {

    private ResponseXmlUtil() {
    }

    /**
     * 格式化XML字符串
     */
    public static String formatXml(String str) throws Exception {
        Document document;
        document = DocumentHelper.parseText(str);
        // 格式化输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置xml的输出编码
        format.setEncoding(ConstantDefault.UTF_8);
        StringWriter writer = new StringWriter();
        // 格式化输出流
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        // 将document写入到输出流
        xmlWriter.write(document);
        xmlWriter.close();
        return writer.toString();
    }

    /**
     * 将返回数据转换为XML格式(格式化、不省略头信息)
     */
    public static String responseToXml(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            // //编码格式
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            // 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 是否省略xm头声明信息
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 将返回数据转换为XML格式(不格式化、省略头信息)
     */
    public static String responseToNoHeadXml(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            //编码格式
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            // 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
            // 是否省略xm头声明信息
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * xml 转 对象
     */
    public static <T> T xml2Bean(String xmlStr, Class<T> clazz) {
        T obj = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            obj = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
        } catch (JAXBException ex) {
            log.error("xml 转 对象异常", ex);
        }
        return obj;
    }

    /**
     * 定义接口调用返回失败方法
     */
    public static String responseDefeat(String info) {
        ResponseDefeatBean defeat = new ResponseDefeatBean();
        defeat.setCode(info);
        defeat.setMsg(SystemConst.RESPONSE_DEFEAT);
        return responseToXml(defeat);
    }

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bst@微胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值