温馨提示×

Java中JSON数据的压缩与解压

小樊
89
2024-08-17 13:42:40
栏目: 编程语言

在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对象。

0