如何在Java中压缩JSON并在Javascript中解压缩 [英] How to Compress JSON in java and decompression in Javascript
问题描述
我有大量数据从服务器发送到Javascript,这需要很长时间才能加载。
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.
推荐答案
要压缩你的字符串你可以使用:
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来自java.util.zip
GZIPOutputStream is from java.util.zip
大多数浏览器应该能够处理gzip压缩内容而无需手动解压缩。
Most browsers should be able to handle gzip compressed content without the need of manual decompression.
文档: GZIPOutputStream
如果您使用的是Ajax,请参阅使用AJAX加载GZIP JSON文件客户端的数据采集。有必要将响应的标题设置为 @hgoebl
。
See Loading GZIP JSON file using AJAX if you're using Ajax for the data acquisition on the client-side. It is necessary to set the headers for your response as @hgoebl
mentioned.
这篇关于如何在Java中压缩JSON并在Javascript中解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!