Skip to content

Commit

Permalink
improved gzip bytes support, fix #3614
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Apr 5, 2021
1 parent 9613771 commit e2f9cc6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/main/java/com/alibaba/fastjson/JSON.java
Expand Up @@ -15,10 +15,7 @@
*/
package com.alibaba.fastjson;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
Expand All @@ -27,6 +24,7 @@
import java.nio.charset.CharsetDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;

import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.*;
Expand Down Expand Up @@ -444,14 +442,31 @@ public static <T> T parseObject(byte[] bytes, int offset, int len,
charset = IOUtils.UTF8;
}

String strVal;
String strVal = null;
if (charset == IOUtils.UTF8) {
char[] chars = allocateChars(bytes.length);
int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars);

if (chars_len < 0) {
InputStreamReader gzipReader = null;
try {
gzipReader = new InputStreamReader(
new GZIPInputStream(
new ByteArrayInputStream(bytes, offset, len)), "UTF-8");
strVal = IOUtils.readAll(gzipReader);
} catch (Exception ex) {
return null;
} finally {
IOUtils.close(gzipReader);
}
}
if (strVal == null && chars_len < 0) {
return null;
}
strVal = new String(chars, 0, chars_len);

if (strVal == null) {
strVal = new String(chars, 0, chars_len);
}
} else {
if (len < 0) {
return null;
Expand Down
32 changes: 32 additions & 0 deletions src/test/java/com/alibaba/json/bvt/issue_3600/Issue3614.java
@@ -0,0 +1,32 @@
package com.alibaba.json.bvt.issue_3600;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import junit.framework.TestCase;

import java.io.ByteArrayOutputStream;
import java.io.*;
import java.util.Collections;
import java.util.zip.GZIPOutputStream;

public class Issue3614 extends TestCase {
public void test_for_issue() throws Exception {
byte[] gzipBytes = gzip(JSON.toJSONString(Collections.singletonMap("key", "value")).getBytes());

Object o = JSON.parseObject(gzipBytes, JSONObject.class);
assertEquals("{\"key\":\"value\"}", JSON.toJSONString(o));
}

private static byte[] gzip(byte[] source) throws IOException {
if (source == null) return null;

ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(source);
gzip.finish();
byte[] bytes = bos.toByteArray();
gzip.close();
return bytes;
}

}

0 comments on commit e2f9cc6

Please sign in to comment.