如何将Gzip类型的数据解压成Json类型的数据格式

 

使用和风天气的时候出现了Gzip压缩后的Json数据。前端需要使用Json类型的数据,那么我么就要对该数据进行一步解压。以下是解压的函数。

/**
 * 将压缩的字节流数据解压缩为JSONObject对象
 *
 * @param data 压缩过的字节数组
 * @return 返回解压缩后的JSONObject对象,如果解压缩过程中发生错误则返回null
 */
private JSONObject decompressStringToJson(byte[] data){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try{
        // 创建GZIP输入流以便解压缩
        GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(data));
        byte[] buffer = new byte[1024];
        int read;
        // 读取压缩数据并写入输出流
        while ((read = gzip.read(buffer)) != -1){
               stream.write(buffer, 0, read);
        }
        // 关闭流
        gzip.close();
        stream.close();
        // 将解压缩后的数据转换为JSONObject并返回
        return JSONObject.parseObject(stream.toString());
    }catch (IOException e){
        // 如果发生IO异常,返回null
        return null;
    }
}

这里的 data填写调用api返回过来的数据。比如下面的这段代码。

private WeatherVO fetchFromCache(double longitude, double latitude){

            // 根据经纬度获取城市信息
            // 调用气象服务API完成地理位置反查
            JSONObject geo = this.decompressStringToJson( rest.getForObject("https://geoapi.qweather.com/v2/city/lookup?location="+longitude+","+latitude+"&key="+key, byte[].class));

            if(geo == null) return null;
            JSONObject location = geo.getJSONObject("location");
            int id = location.getInteger("id");
            String key = "weather:" + id;
            String cache = template.opsForValue().get(key);


            if(cache != null)
                return JSONObject.parseObject(cache).to(WeatherVO.class);
            WeatherVO vo = this.fetchFromAPI(id,location);
            if(vo == null) return  null;
            template.opsForValue().set(key, JSONObject.from(vo).toJSONString(),1, TimeUnit.HOURS);
            return vo;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值