Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compress JSON in java and decompression in Javascript [closed]

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

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

like image 338
user3118357 Avatar asked Dec 19 '13 08:12

user3118357


1 Answers

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

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

Docs: GZIPOutputStream

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.

like image 121
Dropout Avatar answered Oct 19 '22 12:10

Dropout