fix slash escape bug

This commit is contained in:
Looly 2020-04-25 09:31:39 +08:00
parent 669d19eab8
commit 2bcad6031d
5 changed files with 24 additions and 13 deletions

View File

@ -3,10 +3,11 @@
-------------------------------------------------------------------------------------------------------------
## 5.3.3 (2020-04-23)
## 5.3.3 (2020-04-25)
### 新特性
### Bug修复
* 【json 】 修复JSON转字符串时</被转义问题
-------------------------------------------------------------------------------------------------------------

View File

@ -31,7 +31,7 @@ final class InternalJSONUtil {
*
* @param writer Writer
* @param value
* @param indentFactor 每一级别的缩进量
* @param indentFactor 缩进因子定义每一级别增加的缩进量
* @param indent 缩进空格数
* @param config 配置项
* @return Writer

View File

@ -599,13 +599,13 @@ public final class JSONUtil {
}
char b; // 前一个字符
char c = 0; // 当前字符
char c; // 当前字符
int len = str.length();
if (isWrap) {
writer.write('"');
}
for (int i = 0; i < len; i++) {
b = c;
// b = c;
c = str.charAt(i);
switch (c) {
case '\\':
@ -613,12 +613,13 @@ public final class JSONUtil {
writer.write("\\");
writer.write(c);
break;
case '/':
if (b == '<') {
writer.write('\\');
}
writer.write(c);
break;
//此处转义导致输出不和预期一致
// case '/':
// if (b == '<') {
// writer.write('\\');
// }
// writer.write(c);
// break;
default:
writer.write(escape(c));
}

View File

@ -142,6 +142,15 @@ public class JSONObjectTest {
Console.log(json2);
}
@Test
public void parseStringWithSlashTest() {
//在5.3.2之前</div>中的/会被转义修复此bug的单元测试
String jsonStr = "{\"a\":\"<div>aaa</div>\"}";
JSONObject json = new JSONObject(jsonStr);
Assert.assertEquals("<div>aaa</div>", json.get("a"));
Assert.assertEquals(jsonStr, json.toString());
}
@Test
public void toBeanTest() {
JSONObject subJson = JSONUtil.createObj().set("value1", "strValue1").set("value2", "234");

View File

@ -93,11 +93,11 @@ public class JSONUtilTest {
map.put("user", object.toString());
JSONObject json = JSONUtil.parseObj(map);
Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"<\\/\"}", json.get("user"));
Assert.assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"<\\\\/\\\"}\"}", json.toString());
Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.get("user"));
Assert.assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"</\\\"}\"}", json.toString());
JSONObject json2 = JSONUtil.parseObj(json.toString());
Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"<\\/\"}", json2.get("user"));
Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.get("user"));
}
/**