为了账号安全,请及时绑定邮箱和手机立即绑定

Java -- GSon实现json序列化和反序列化 (Restful API Test)

标签:
Java 测试
package com.yuyong.Action;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuyong.Model.Bean;
import com.yuyong.Model.Head;
import com.yuyong.Model.PaymentCurrencyList;

public class MainAction {

    // 读取Json文件
    public String readJsonData(String path) {
        String data = "";
        File file = new File(path);
        if (file.isFile() && file.exists()) {
            try {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    data += lineTxt;
                }
                read.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data.toString();
    }

    // 将Json数据和Bean实体类相互转换
    public static void main(String[] args) throws Exception {
        // Bean类实体对象转成json数据
        Bean bean = new Bean();
        bean.setDCity("SHA");
        bean.setACity("SEL");
        bean.setDDate("2016-12-31");
        bean.setOffSet("0");

        Head head = new Head();
        head.setLanguage("ENGLISH");
        head.setSource("Online");
        head.setCurrency("CNY");
        head.setUID("D111111");
        head.setIsQuickBooking("0");
        head.setAPIKey("CtripOnline");
        head.setClientSignTime("0");
        head.setSubChannel("0");

        PaymentCurrencyList PaymentCurrencyList = new PaymentCurrencyList();
        PaymentCurrencyList.setListA("AAA");
        PaymentCurrencyList.setListB("BBB");

        List<PaymentCurrencyList> currencyList = new ArrayList<>();
        currencyList.add(PaymentCurrencyList);

        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("bean", bean);
        map.put("head", head);
        map.put("currency", currencyList);

        Gson gson = new Gson();
        String s = gson.toJson(map);
        System.out.println(s);

        System.out.println("------------------------------------------------------------------------------------");
        // 一般情况下,我们从服务器返回来的数据是json数据,所以我们需要把它转成bean对应的实体类
        // 这里有一点要注意的是,我们进行一般的转换,需要json和bean的属性数量和属性类型和名称都要对应完全一致
        // 否则可能会报错
        String path = "D:\\jsonData.txt";
        MainAction fo = new MainAction();
        String str = fo.readJsonData(path);

        Map<String, Object> retMap = gson.fromJson(str, new TypeToken<Map<String, Object>>() {
        }.getType());

        for (String key : retMap.keySet()) {
            System.out.println("key: " + key + "  values:" + retMap.get(key));
        }

        System.out.println("-=-=-=->> bean.toString: " + retMap.toString());

        URL url = new URL("https://echo.getpostman.com/post");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true); // 设置允许输入
        conn.setDoInput(true); // 设置允许输出
        conn.setUseCaches(false); // 设置不用缓存
        conn.setRequestMethod("POST"); // 设置传递方式
        conn.setRequestProperty("Connection", "Keep-Alive"); // 设置维持长连接
        conn.setRequestProperty("Charset", "UTF-8"); // 设置文件字符集
        byte[] data = (retMap.toString()).getBytes("UTF-8"); // 转换为字节数组
        conn.setRequestProperty("Content-Length", String.valueOf(data.length)); // 设置文件长度
        conn.setRequestProperty("contentType", "application/json"); // 设置文件类型

        conn.connect(); // 开始连接请求
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // UTF-8编码
        out.write(retMap.toString());
        out.flush();
        out.close();

        System.out.println(conn.getResponseCode());

        if (conn.getResponseCode() == 200) {
            System.out.println("恭喜!连接成功!");

            // arraycopy(被复制的源数组, 从第几个元素开始复制, 要粘贴到的目标数组, 从第几个元素开始粘贴,
            // 一共需要复制的元素个数);
            int length = (int) conn.getContentLength(); // 获取长度
            InputStream in = conn.getInputStream(); // 获取输入io流对象
            if (length != -1) {
                byte[] dest = new byte[length];
                byte[] src = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = in.read(src)) >= 0) {
                    System.arraycopy(src, 0, dest, destPos, readLen);
                    destPos = destPos + readLen;
                }
                String result = new String(dest, "UTF-8"); // UTF-8编码
                System.out.println(result);
                // System.out.println("解压缩后字符串:" +
                // MainAction.uncompressToString(data1, result));
            }
        } else {
            System.out.println("error!");
        }
    }

    public static String uncompressToString(byte[] data1, String result) {
        if (data1 == null || data1.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(data1);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
软件测试工程师
手记
粉丝
7
获赞与收藏
180

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消