diff --git a/src/main/java/com/alibaba/fastjson/JSON.java b/src/main/java/com/alibaba/fastjson/JSON.java index e43548ec8c..d1a76db889 100644 --- a/src/main/java/com/alibaba/fastjson/JSON.java +++ b/src/main/java/com/alibaba/fastjson/JSON.java @@ -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; @@ -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.*; @@ -444,14 +442,31 @@ public static 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; diff --git a/src/test/java/com/alibaba/json/bvt/issue_3600/Issue3614.java b/src/test/java/com/alibaba/json/bvt/issue_3600/Issue3614.java new file mode 100644 index 0000000000..cdded5b5e9 --- /dev/null +++ b/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; + } + +}