Java中JSON數(shù)據(jù)的壓縮與解壓

小樊
94
2024-08-17 13:42:40

在Java中,可以使用GZIP進(jìn)行JSON數(shù)據(jù)的壓縮和解壓縮操作。以下是一個(gè)示例代碼:

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數(shù)據(jù)
    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數(shù)據(jù)
    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數(shù)據(jù)
            byte[] compressedData = compressJSON(json);
            System.out.println("Compressed data: " + compressedData);

            // 解壓縮JSON數(shù)據(jù)
            JSONObject decompressedJson = decompressJSON(compressedData);
            System.out.println("Decompressed JSON: " + decompressedJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我們定義了compressJSON方法用于壓縮JSON數(shù)據(jù),decompressJSON方法用于解壓縮JSON數(shù)據(jù)。在main方法中,我們創(chuàng)建一個(gè)簡(jiǎn)單的JSON對(duì)象,然后進(jìn)行壓縮和解壓縮操作。最后打印壓縮后的數(shù)據(jù)和解壓縮后的JSON對(duì)象。

0