如何在 Java 中压缩 JSON 并在 Javascript 中解压

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20676831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:31:48  来源:igfitidea点击:

How to Compress JSON in java and decompression in Javascript

javajavascriptjson

提问by user3118357

I have a large amount of data being sent from server to Javascript, which is taking quite a long time to load.

我有大量数据从服务器发送到 Javascript,加载需要很长时间。

I was wondering how I can implement compression at server and decompression in Javascript. I would appreciate any help.

我想知道如何在服务器上实现压缩并在 Javascript 中解压缩。我将不胜感激任何帮助。

回答by Dropout

To compress your String you can use:

要压缩您的字符串,您可以使用:

public static String compress(String str) throws IOException {
    if (str == null || str.length() == 0) {
        return str;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    String outStr = out.toString("UTF-8");
    return outStr;
 }

GZIPOutputStream is from java.util.zip

GZIPOutputStream 来自 java.util.zip

Most browsers should be able to handle gzip compressed content without the need of manual decompression.

大多数浏览器应该能够处理 gzip 压缩内容,而无需手动解压缩。

Docs: GZIPOutputStream

文档:GZIPOutputStream

See Loading GZIP JSON file using AJAXif you're using Ajax for the data acquisition on the client-side. It is necessary to set the headers for your response as @hgoeblmentioned.

如果您使用 Ajax 在客户端获取数据,请参阅使用 AJAX 加载 GZIP JSON 文件@hgoebl如上所述,有必要为您的响应设置标头。