在Java中,可以使用GZIP進行JSON數據的壓縮和解壓縮操作。以下是一個示例代碼:
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class JSONCompression {
// 壓縮JSON數據
public static byte[] compressJSON(JSONObject json) throws IOException {
byte[] jsonData = json.toString().getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) {
gzipOut.write(jsonData);
}
return baos.toByteArray();
}
// 解壓縮JSON數據
public static JSONObject decompressJSON(byte[] compressedData) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(compressedData);
try (GZIPInputStream gzipIn = new GZIPInputStream(bais)) {
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
while ((len = gzipIn.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
String decompressedData = baos.toString();
return new JSONObject(decompressedData);
}
}
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("key1", "value1");
json.put("key2", "value2");
try {
// 壓縮JSON數據
byte[] compressedData = compressJSON(json);
System.out.println("Compressed data: " + compressedData);
// 解壓縮JSON數據
JSONObject decompressedJson = decompressJSON(compressedData);
System.out.println("Decompressed JSON: " + decompressedJson);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們定義了compressJSON
方法用于壓縮JSON數據,decompressJSON
方法用于解壓縮JSON數據。在main
方法中,我們創建一個簡單的JSON對象,然后進行壓縮和解壓縮操作。最后打印壓縮后的數據和解壓縮后的JSON對象。