我想在JavaScript中压缩大型JSON对象,然后在Java中解压缩

时间:2019-02-05 05:20:20

标签: javascript java compression

我想在javascript中压缩大型JSON对象并在java中解压缩它。什么是最佳压缩算法将支持此功能?

继续,我尝试使用gzip来解决这个问题。

我将javascript作为客户端,并将Java Jboss Resteasy置于服务器端。我尝试了您的方法不起作用。我在javascript中使用zlib库使用Gzip进行了压缩,并使用Content Encoding作为gzip,也使用了Gzip Jboss服务器端的注解自动解压缩。它不起作用。此外,我尝试使用InputStreamReader在Java中解压缩,它抛出“数据未采用Gzip格式”错误。请在这里帮助我,如果可以的话粘贴相同的示例代码

JavaScript代码

 zlib.gzip(JSON.stringify($scope.jsonCompressCheck),function(err, buffer) {
            if (!err) {
              console.log("USing gzip: ");
              console.log("Byte Length: "+Buffer.byteLength(buffer));
              console.log(sizeof(buffer));

             $scope.compressed = buffer;
             var buf2 = Buffer.from(JSON.stringify($scope.jsonCompressCheck));

        $http.post(ATS_URL + ATS_INSTANCE + '/rest/private/decompress/' + clientName + '/gzipdecompress', ($scope.compressed), {

            contentType: 'application/json',
            contentEncoding: 'gzip'

        }).success(function (data, status, headers) {

            console.log("Output Response :- "+data+" Headers: "+headers+"  status: "+status);

        }).error(function (reason) {

            console.log(" Error reason "+reason);
        });

此处的Java代码:Jboss RestEasy 端点

@POST @NoCache
@ApiOperation(value = "Decompress Given Compressed Json object Using Gzip",
                    response = ElasticSearchResults.class, position = 0)
@Path("/{client}/gzipdecompress")
public String gzipJsonDecompress(
        @ApiParam(value = "This required field should be the client name as defined in the datasources.", required = true)
        @PathParam("client") String client,
        @GZIP byte[] compressedObject) throws ATSException {
     return decompressService.gzipJsonDecompress(client,compressedObject);
}

实施代码

 public String gzipJsonDecompress(String client,byte[] compressedObject)throws ATSException{

    validateDomain(client);

    try
    {    InputStream inputStream = new 
         ByteArrayInputStream(compressedObject);
        GZIPInputStream gzipInput = new GZIPInputStream(inputStream); //Not working here  
         ....

2 个答案:

答案 0 :(得分:0)

最合适的压缩可能是GZip。您可以上传使用GZip压缩的内容,并将服务器设置为处理Content-Encoding标头,以便在服务器端自动将其解压缩。请看以下链接。 enter link description here

答案 1 :(得分:0)

public async Task<IHttpActionResult> ValidateSesion()
{
    var values = new Dictionary<string, string>{
      { "productId", "1" },
      { "productKey", "Abc6666" },
      { "userName", "OPPO" },
    };

    var json = JsonConvert.SerializeObject(values, Formatting.Indented);

    var stringContent = new StringContent(json);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsync("http://172.116.12.172:8014/iadmin/validate", stringContent);

    var responseString = await response.Content.ReadAsStringAsync();

    return Ok(responseString);
}