使用和风天气的时候出现了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;
}