add exception for json

This commit is contained in:
Looly
2022-11-29 21:50:51 +08:00
parent bc808210fd
commit 68d28c4fd4
9 changed files with 137 additions and 21 deletions

View File

@@ -0,0 +1,24 @@
package cn.hutool.json;
import cn.hutool.core.text.StrUtil;
import org.junit.Assert;
import org.junit.Test;
public class Issue2746Test {
@Test
public void parseObjTest() {
final String str = StrUtil.repeat("{", 1500) + StrUtil.repeat("}", 1500);
try{
JSONUtil.parseObj(str);
} catch (final JSONException e){
Assert.assertTrue(e.getMessage().startsWith("A JSONObject can not directly nest another JSONObject or JSONArray"));
}
}
@Test(expected = JSONException.class)
public void parseTest() {
final String str = StrUtil.repeat("[", 1500) + StrUtil.repeat("]", 1500);
JSONUtil.parseArray(str);
}
}

View File

@@ -0,0 +1,37 @@
package cn.hutool.json;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* https://github.com/dromara/hutool/issues/2749
* <p>
* 由于使用了递归方式解析和写出导致JSON太长的话容易栈溢出。
*/
public class Issue2749Test {
@Test
@Ignore
public void jsonObjectTest() {
final Map<String, Object> map = new HashMap<>(1, 1f);
Map<String, Object> node = map;
for (int i = 0; i < 1000; i++) {
//noinspection unchecked
node = (Map<String, Object>) node.computeIfAbsent("a", k -> new HashMap<String, Object>(1, 1f));
}
node.put("a", 1);
final String jsonStr = JSONUtil.toJsonStr(map);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
final JSONObject jsonObject = new JSONObject(jsonStr);
Assert.assertNotNull(jsonObject);
// 栈溢出
//noinspection ResultOfMethodCallIgnored
jsonObject.toString();
}
}