在JSON中进行数据压缩和解压缩可以使用压缩算法来减小JSON数据的大小。常用的压缩算法有Gzip、Bzip2、Snappy等。以下是一些常用的压缩和解压缩方法:
// 压缩JSON数据
var data = JSON.stringify({message: 'hello world'});
var compressed = pako.deflate(data, {to: 'string'});
// 解压缩JSON数据
var decompressed = pako.inflate(compressed, {to: 'string'});
var json = JSON.parse(decompressed);
console.log(json.message); // 输出 "hello world"
import json
import gzip
# 压缩JSON数据
data = json.dumps({"message": "hello world"}).encode('utf-8')
compressed = gzip.compress(data)
# 解压缩JSON数据
decompressed = gzip.decompress(compressed)
jsonString = decompressed.decode('utf-8')
jsonObject = json.loads(jsonString)
print(jsonObject['message']) # 输出 "hello world"
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
public static byte[] gzip(byte[] input) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(input);
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static byte[] ungzip(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = gis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
gis.close();
bis.close();
bos.close();
return bos.toByteArray();
}
}
// 压缩JSON数据
String data = "{\"message\": \"hello world\"}";
byte[] input = data.getBytes("utf-8");
byte[] compressed = GzipUtils.gzip(input);
// 解压缩JSON数据
byte[] decompressed = GzipUtils.ungzip(compressed);
String jsonString = new String(decompressed, "utf-8");
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject.getString("message")); // 输出 "hello world"