!875 fix 普通byte数组转JSONArray时的异常

Merge pull request !875 from emptypoint/fix-ObjectMapper-byteArray
This commit is contained in:
Looly 2022-11-24 05:21:52 +00:00 committed by Gitee
commit 03088bb05e
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 23 additions and 2 deletions

View File

@ -145,7 +145,8 @@ public class ObjectMapper {
mapFromTokener(new JSONTokener((InputStream) source, jsonArray.getConfig()), jsonArray, filter);
} else if (source instanceof byte[]) {
final byte[] bytesSource = (byte[]) source;
if('[' == bytesSource[0] && ']' == bytesSource[bytesSource.length - 1]){
// 如果是普通的的byte[], 要避免下标越界
if (bytesSource.length > 1 && '[' == bytesSource[0] && ']' == bytesSource[bytesSource.length - 1]) {
mapFromTokener(new JSONTokener(IoUtil.toStream(bytesSource), jsonArray.getConfig()), jsonArray, filter);
}else{
// https://github.com/dromara/hutool/issues/2369

View File

@ -9,6 +9,7 @@ import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.test.bean.Price;
import cn.hutool.json.test.bean.UserA;
import cn.hutool.json.test.bean.UserC;
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
@ -244,10 +245,29 @@ public class JSONUtilTest {
}
@Test(expected = JSONException.class)
public void duplicateKeyTrueTest(){
public void duplicateKeyTrueTest() {
final String str = "{id:123, name:\"张三\", name:\"李四\"}";
final JSONObject jsonObject = JSONUtil.parseObj(str, JSONConfig.create().setCheckDuplicate(true));
Assert.assertEquals("{\"id\":123,\"name\":\"李四\"}", jsonObject.toString());
}
/**
* 测试普通数组转JSONArray时是否异常, 尤其是byte[]数组, 可能是普通的byte[]数组, 也可能是二进制流
*/
@Test
public void testArrayEntity() {
final String jsonStr = JSONUtil.toJsonStr(new ArrayEntity());
Assert.assertEquals("{\"a\":[],\"b\":[0],\"c\":[],\"d\":[],\"e\":[]}", jsonStr);
}
@Data
static class ArrayEntity {
private byte[] a = new byte[0];
private byte[] b = new byte[1];
private int[] c = new int[0];
private Byte[] d = new Byte[0];
private Byte[] e = new Byte[1];
}
}