This commit is contained in:
Looly 2022-09-05 12:20:34 +08:00
parent d141efea62
commit 5b2d2050d2
5 changed files with 130 additions and 103 deletions

View File

@ -6,6 +6,8 @@ import cn.hutool.core.lang.Editor;
import cn.hutool.core.lang.func.Func1; import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil; import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -70,8 +72,19 @@ public class CopyOptions implements Serializable {
/** /**
* 自定义类型转换器默认使用全局万能转换器转换 * 自定义类型转换器默认使用全局万能转换器转换
*/ */
protected TypeConverter converter = (type, value) -> protected TypeConverter converter = (type, value) -> {
Convert.convertWithCheck(type, value, null, ignoreError); if(null == value){
return null;
}
final String name = value.getClass().getName();
if(ArrayUtil.contains(new String[]{"cn.hutool.json.JSONObject", "cn.hutool.json.JSONArray"}, name)){
// 由于设计缺陷导致JSON转Bean时无法使用自定义的反序列化器此处采用反射方式修复bug此类问题会在6.x解决
return ReflectUtil.invoke(value, "toBean", ObjectUtil.defaultIfNull(type, Object.class));
}
return Convert.convertWithCheck(type, value, null, ignoreError);
};
//region create //region create

View File

@ -55,7 +55,7 @@ public abstract class AbstractConverter<T> implements Converter<T>, Serializable
// 除Map外已经是目标类型不需要转换Map类型涉及参数类型需要单独转换 // 除Map外已经是目标类型不需要转换Map类型涉及参数类型需要单独转换
return targetType.cast(value); return targetType.cast(value);
} }
T result = convertInternal(value); final T result = convertInternal(value);
return ((null == result) ? defaultValue : result); return ((null == result) ? defaultValue : result);
} else { } else {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -80,7 +80,7 @@ public class JSONConverter implements Converter<JSON> {
final Class<?> clazz = (Class<?>) targetType; final Class<?> clazz = (Class<?>) targetType;
if (JSONBeanParser.class.isAssignableFrom(clazz)){ if (JSONBeanParser.class.isAssignableFrom(clazz)){
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
JSONBeanParser target = (JSONBeanParser) ReflectUtil.newInstanceIfPossible(clazz); final JSONBeanParser target = (JSONBeanParser) ReflectUtil.newInstanceIfPossible(clazz);
if(null == target){ if(null == target){
throw new ConvertException("Can not instance [{}]", targetType); throw new ConvertException("Can not instance [{}]", targetType);
} }

View File

@ -1,4 +1,5 @@
import cn.hutool.json.JSON; import cn.hutool.json.JSON;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import cn.hutool.json.serialize.JSONDeserializer; import cn.hutool.json.serialize.JSONDeserializer;
@ -23,7 +24,20 @@ public class Issue2555Test {
Assert.assertEquals("{\"myType\":{\"addr\":\"addrValue1\"}}", json); Assert.assertEquals("{\"myType\":{\"addr\":\"addrValue1\"}}", json);
//MyDeserializer不会被调用 //MyDeserializer不会被调用
final SimpleObj simpleObj2 = JSONUtil.toBean(json, SimpleObj.class); final JSONObject jsonObject = JSONUtil.parseObj(json, JSONConfig.create().setIgnoreError(false));
final SimpleObj simpleObj2 = jsonObject.toBean(SimpleObj.class);
Assert.assertEquals("addrValue1", simpleObj2.getMyType().getAddress());
}
@Test
public void deserTest(){
JSONUtil.putDeserializer(MyType.class, new MyDeserializer());
final String jsonStr = "{\"myType\":{\"addr\":\"addrValue1\"}}";
//MyDeserializer不会被调用
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr, JSONConfig.create().setIgnoreError(false));
final SimpleObj simpleObj2 = jsonObject.toBean(SimpleObj.class);
Assert.assertEquals("addrValue1", simpleObj2.getMyType().getAddress()); Assert.assertEquals("addrValue1", simpleObj2.getMyType().getAddress());
} }

View File

@ -50,8 +50,8 @@ public class JSONObjectTest {
@Test @Test
@Ignore @Ignore
public void toStringTest() { public void toStringTest() {
String str = "{\"code\": 500, \"data\":null}"; final String str = "{\"code\": 500, \"data\":null}";
JSONObject jsonObject = new JSONObject(str); final JSONObject jsonObject = new JSONObject(str);
Console.log(jsonObject); Console.log(jsonObject);
jsonObject.getConfig().setIgnoreNullValue(true); jsonObject.getConfig().setIgnoreNullValue(true);
Console.log(jsonObject.toStringPretty()); Console.log(jsonObject.toStringPretty());
@ -59,9 +59,9 @@ public class JSONObjectTest {
@Test @Test
public void toStringTest2() { public void toStringTest2() {
String str = "{\"test\":\"关于开展2018年度“文明集体”、“文明职工”评选表彰活动的通知\"}"; final String str = "{\"test\":\"关于开展2018年度“文明集体”、“文明职工”评选表彰活动的通知\"}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(str); final JSONObject json = new JSONObject(str);
Assert.assertEquals(str, json.toString()); Assert.assertEquals(str, json.toString());
} }
@ -70,7 +70,7 @@ public class JSONObjectTest {
*/ */
@Test @Test
public void toStringTest3() { public void toStringTest3() {
JSONObject json = Objects.requireNonNull(JSONUtil.createObj()// final JSONObject json = Objects.requireNonNull(JSONUtil.createObj()//
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))// .set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
.setDateFormat(DatePattern.NORM_DATE_PATTERN); .setDateFormat(DatePattern.NORM_DATE_PATTERN);
Assert.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString()); Assert.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
@ -89,13 +89,13 @@ public class JSONObjectTest {
@Test @Test
public void putAllTest() { public void putAllTest() {
JSONObject json1 = JSONUtil.createObj() final JSONObject json1 = JSONUtil.createObj()
.set("a", "value1") .set("a", "value1")
.set("b", "value2") .set("b", "value2")
.set("c", "value3") .set("c", "value3")
.set("d", true); .set("d", true);
JSONObject json2 = JSONUtil.createObj() final JSONObject json2 = JSONUtil.createObj()
.set("a", "value21") .set("a", "value21")
.set("b", "value22"); .set("b", "value22");
@ -109,8 +109,8 @@ public class JSONObjectTest {
@Test @Test
public void parseStringTest() { public void parseStringTest() {
String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}"; final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
JSONObject jsonObject = JSONUtil.parseObj(jsonStr); final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
Assert.assertEquals(jsonObject.get("a"), "value1"); Assert.assertEquals(jsonObject.get("a"), "value1");
Assert.assertEquals(jsonObject.get("b"), "value2"); Assert.assertEquals(jsonObject.get("b"), "value2");
Assert.assertEquals(jsonObject.get("c"), "value3"); Assert.assertEquals(jsonObject.get("c"), "value3");
@ -122,57 +122,57 @@ public class JSONObjectTest {
@Test @Test
public void parseStringTest2() { public void parseStringTest2() {
String jsonStr = "{\"file_name\":\"RMM20180127009_731.000\",\"error_data\":\"201121151350701001252500000032 18973908335 18973908335 13601893517 201711211700152017112115135420171121 6594000000010100000000000000000000000043190101701001910072 100001100 \",\"error_code\":\"F140\",\"error_info\":\"最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”\",\"app_name\":\"inter-pre-check\"}"; final String jsonStr = "{\"file_name\":\"RMM20180127009_731.000\",\"error_data\":\"201121151350701001252500000032 18973908335 18973908335 13601893517 201711211700152017112115135420171121 6594000000010100000000000000000000000043190101701001910072 100001100 \",\"error_code\":\"F140\",\"error_info\":\"最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”\",\"app_name\":\"inter-pre-check\"}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(jsonStr); final JSONObject json = new JSONObject(jsonStr);
Assert.assertEquals("F140", json.getStr("error_code")); Assert.assertEquals("F140", json.getStr("error_code"));
Assert.assertEquals("最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”", json.getStr("error_info")); Assert.assertEquals("最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”", json.getStr("error_info"));
} }
@Test @Test
public void parseStringTest3() { public void parseStringTest3() {
String jsonStr = "{\"test\":\"体”、“文\"}"; final String jsonStr = "{\"test\":\"体”、“文\"}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(jsonStr); final JSONObject json = new JSONObject(jsonStr);
Assert.assertEquals("体”、“文", json.getStr("test")); Assert.assertEquals("体”、“文", json.getStr("test"));
} }
@Test @Test
public void parseStringTest4() { public void parseStringTest4() {
String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}"; final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(jsonStr); final JSONObject json = new JSONObject(jsonStr);
Assert.assertEquals(new Integer(0), json.getInt("ok")); Assert.assertEquals(new Integer(0), json.getInt("ok"));
Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards")); Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
} }
@Test @Test
public void parseBytesTest() { public void parseBytesTest() {
String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}"; final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(jsonStr.getBytes(StandardCharsets.UTF_8)); final JSONObject json = new JSONObject(jsonStr.getBytes(StandardCharsets.UTF_8));
Assert.assertEquals(new Integer(0), json.getInt("ok")); Assert.assertEquals(new Integer(0), json.getInt("ok"));
Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards")); Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
} }
@Test @Test
public void parseReaderTest() { public void parseReaderTest() {
String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}"; final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
final StringReader stringReader = new StringReader(jsonStr); final StringReader stringReader = new StringReader(jsonStr);
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(stringReader); final JSONObject json = new JSONObject(stringReader);
Assert.assertEquals(new Integer(0), json.getInt("ok")); Assert.assertEquals(new Integer(0), json.getInt("ok"));
Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards")); Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
} }
@Test @Test
public void parseInputStreamTest() { public void parseInputStreamTest() {
String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}"; final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
final ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8)); final ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(in); final JSONObject json = new JSONObject(in);
Assert.assertEquals(new Integer(0), json.getInt("ok")); Assert.assertEquals(new Integer(0), json.getInt("ok"));
Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards")); Assert.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
} }
@ -180,9 +180,9 @@ public class JSONObjectTest {
@Test @Test
@Ignore @Ignore
public void parseStringWithBomTest() { public void parseStringWithBomTest() {
String jsonStr = FileUtil.readUtf8String("f:/test/jsontest.txt"); final String jsonStr = FileUtil.readUtf8String("f:/test/jsontest.txt");
JSONObject json = new JSONObject(jsonStr); final JSONObject json = new JSONObject(jsonStr);
JSONObject json2 = JSONUtil.parseObj(json); final JSONObject json2 = JSONUtil.parseObj(json);
Console.log(json); Console.log(json);
Console.log(json2); Console.log(json2);
} }
@ -190,23 +190,23 @@ public class JSONObjectTest {
@Test @Test
public void parseStringWithSlashTest() { public void parseStringWithSlashTest() {
//在5.3.2之前</div>中的/会被转义修复此bug的单元测试 //在5.3.2之前</div>中的/会被转义修复此bug的单元测试
String jsonStr = "{\"a\":\"<div>aaa</div>\"}"; final String jsonStr = "{\"a\":\"<div>aaa</div>\"}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject json = new JSONObject(jsonStr); final JSONObject json = new JSONObject(jsonStr);
Assert.assertEquals("<div>aaa</div>", json.get("a")); Assert.assertEquals("<div>aaa</div>", json.get("a"));
Assert.assertEquals(jsonStr, json.toString()); Assert.assertEquals(jsonStr, json.toString());
} }
@Test @Test
public void toBeanTest() { public void toBeanTest() {
JSONObject subJson = JSONUtil.createObj().set("value1", "strValue1").set("value2", "234"); final JSONObject subJson = JSONUtil.createObj().set("value1", "strValue1").set("value2", "234");
JSONObject json = JSONUtil.createObj().set("strValue", "strTest").set("intValue", 123) final JSONObject json = JSONUtil.createObj().set("strValue", "strTest").set("intValue", 123)
// 测试空字符串转对象 // 测试空字符串转对象
.set("doubleValue", "") .set("doubleValue", "")
.set("beanValue", subJson) .set("beanValue", subJson)
.set("list", JSONUtil.createArray().set("a").set("b")).set("testEnum", "TYPE_A"); .set("list", JSONUtil.createArray().set("a").set("b")).set("testEnum", "TYPE_A");
TestBean bean = json.toBean(TestBean.class); final TestBean bean = json.toBean(TestBean.class);
Assert.assertEquals("a", bean.getList().get(0)); Assert.assertEquals("a", bean.getList().get(0));
Assert.assertEquals("b", bean.getList().get(1)); Assert.assertEquals("b", bean.getList().get(1));
@ -219,14 +219,14 @@ public class JSONObjectTest {
@Test @Test
public void toBeanNullStrTest() { public void toBeanNullStrTest() {
JSONObject json = JSONUtil.createObj()// final JSONObject json = JSONUtil.createObj()//
.set("strValue", "null")// .set("strValue", "null")//
.set("intValue", 123)// .set("intValue", 123)//
// 子对象对应"null"字符串如果忽略错误跳过否则抛出转换异常 // 子对象对应"null"字符串如果忽略错误跳过否则抛出转换异常
.set("beanValue", "null")// .set("beanValue", "null")//
.set("list", JSONUtil.createArray().set("a").set("b")); .set("list", JSONUtil.createArray().set("a").set("b"));
TestBean bean = json.toBean(TestBean.class, true); final TestBean bean = json.toBean(TestBean.class, true);
// 当JSON中为字符串"null"时应被当作字符串处理 // 当JSON中为字符串"null"时应被当作字符串处理
Assert.assertEquals("null", bean.getStrValue()); Assert.assertEquals("null", bean.getStrValue());
// 当JSON中为字符串"null"时Bean中的字段类型不匹配应在ignoreError模式下忽略注入 // 当JSON中为字符串"null"时Bean中的字段类型不匹配应在ignoreError模式下忽略注入
@ -235,14 +235,14 @@ public class JSONObjectTest {
@Test @Test
public void toBeanTest2() { public void toBeanTest2() {
UserA userA = new UserA(); final UserA userA = new UserA();
userA.setA("A user"); userA.setA("A user");
userA.setName("{\n\t\"body\":{\n\t\t\"loginId\":\"id\",\n\t\t\"password\":\"pwd\"\n\t}\n}"); userA.setName("{\n\t\"body\":{\n\t\t\"loginId\":\"id\",\n\t\t\"password\":\"pwd\"\n\t}\n}");
userA.setDate(new Date()); userA.setDate(new Date());
userA.setSqs(CollectionUtil.newArrayList(new Seq("seq1"), new Seq("seq2"))); userA.setSqs(CollectionUtil.newArrayList(new Seq("seq1"), new Seq("seq2")));
JSONObject json = JSONUtil.parseObj(userA); final JSONObject json = JSONUtil.parseObj(userA);
UserA userA2 = json.toBean(UserA.class); final UserA userA2 = json.toBean(UserA.class);
// 测试数组 // 测试数组
Assert.assertEquals("seq1", userA2.getSqs().get(0).getSeq()); Assert.assertEquals("seq1", userA2.getSqs().get(0).getSeq());
// 测试带换行符等特殊字符转换是否成功 // 测试带换行符等特殊字符转换是否成功
@ -251,33 +251,33 @@ public class JSONObjectTest {
@Test @Test
public void toBeanWithNullTest() { public void toBeanWithNullTest() {
String jsonStr = "{'data':{'userName':'ak','password': null}}"; final String jsonStr = "{'data':{'userName':'ak','password': null}}";
UserWithMap user = JSONUtil.toBean(JSONUtil.parseObj(jsonStr), UserWithMap.class); final UserWithMap user = JSONUtil.toBean(JSONUtil.parseObj(jsonStr), UserWithMap.class);
Assert.assertTrue(user.getData().containsKey("password")); Assert.assertTrue(user.getData().containsKey("password"));
} }
@Test @Test
public void toBeanTest4() { public void toBeanTest4() {
String json = "{\"data\":{\"b\": \"c\"}}"; final String json = "{\"data\":{\"b\": \"c\"}}";
UserWithMap map = JSONUtil.toBean(json, UserWithMap.class); final UserWithMap map = JSONUtil.toBean(json, UserWithMap.class);
Assert.assertEquals("c", map.getData().get("b")); Assert.assertEquals("c", map.getData().get("b"));
} }
@Test @Test
public void toBeanTest5() { public void toBeanTest5() {
String readUtf8Str = ResourceUtil.readUtf8Str("suiteReport.json"); final String readUtf8Str = ResourceUtil.readUtf8Str("suiteReport.json");
JSONObject json = JSONUtil.parseObj(readUtf8Str); final JSONObject json = JSONUtil.parseObj(readUtf8Str);
SuiteReport bean = json.toBean(SuiteReport.class); final SuiteReport bean = json.toBean(SuiteReport.class);
// 第一层 // 第一层
List<CaseReport> caseReports = bean.getCaseReports(); final List<CaseReport> caseReports = bean.getCaseReports();
CaseReport caseReport = caseReports.get(0); final CaseReport caseReport = caseReports.get(0);
Assert.assertNotNull(caseReport); Assert.assertNotNull(caseReport);
// 第二层 // 第二层
List<StepReport> stepReports = caseReports.get(0).getStepReports(); final List<StepReport> stepReports = caseReports.get(0).getStepReports();
StepReport stepReport = stepReports.get(0); final StepReport stepReport = stepReports.get(0);
Assert.assertNotNull(stepReport); Assert.assertNotNull(stepReport);
} }
@ -286,18 +286,18 @@ public class JSONObjectTest {
*/ */
@Test @Test
public void toBeanTest6() { public void toBeanTest6() {
JSONObject json = JSONUtil.createObj() final JSONObject json = JSONUtil.createObj()
.set("targetUrl", "http://test.com") .set("targetUrl", "http://test.com")
.set("success", "true") .set("success", "true")
.set("result", JSONUtil.createObj() .set("result", JSONUtil.createObj()
.set("token", "tokenTest") .set("token", "tokenTest")
.set("userId", "测试用户1")); .set("userId", "测试用户1"));
TokenAuthWarp2 bean = json.toBean(TokenAuthWarp2.class); final TokenAuthWarp2 bean = json.toBean(TokenAuthWarp2.class);
Assert.assertEquals("http://test.com", bean.getTargetUrl()); Assert.assertEquals("http://test.com", bean.getTargetUrl());
Assert.assertEquals("true", bean.getSuccess()); Assert.assertEquals("true", bean.getSuccess());
TokenAuthResponse result = bean.getResult(); final TokenAuthResponse result = bean.getResult();
Assert.assertNotNull(result); Assert.assertNotNull(result);
Assert.assertEquals("tokenTest", result.getToken()); Assert.assertEquals("tokenTest", result.getToken());
Assert.assertEquals("测试用户1", result.getUserId()); Assert.assertEquals("测试用户1", result.getUserId());
@ -309,21 +309,21 @@ public class JSONObjectTest {
*/ */
@Test @Test
public void toBeanTest7() { public void toBeanTest7() {
String jsonStr = " {\"result\":{\"phone\":\"15926297342\",\"appKey\":\"e1ie12e1ewsdqw1\"," + final String jsonStr = " {\"result\":{\"phone\":\"15926297342\",\"appKey\":\"e1ie12e1ewsdqw1\"," +
"\"secret\":\"dsadadqwdqs121d1e2\",\"message\":\"hello world\"},\"code\":100,\"" + "\"secret\":\"dsadadqwdqs121d1e2\",\"message\":\"hello world\"},\"code\":100,\"" +
"message\":\"validate message\"}"; "message\":\"validate message\"}";
ResultDto<?> dto = JSONUtil.toBean(jsonStr, ResultDto.class); final ResultDto<?> dto = JSONUtil.toBean(jsonStr, ResultDto.class);
Assert.assertEquals("validate message", dto.getMessage()); Assert.assertEquals("validate message", dto.getMessage());
} }
@Test @Test
public void parseBeanTest() { public void parseBeanTest() {
UserA userA = new UserA(); final UserA userA = new UserA();
userA.setName("nameTest"); userA.setName("nameTest");
userA.setDate(new Date()); userA.setDate(new Date());
userA.setSqs(CollectionUtil.newArrayList(new Seq(null), new Seq("seq2"))); userA.setSqs(CollectionUtil.newArrayList(new Seq(null), new Seq("seq2")));
JSONObject json = JSONUtil.parseObj(userA, false); final JSONObject json = JSONUtil.parseObj(userA, false);
Assert.assertTrue(json.containsKey("a")); Assert.assertTrue(json.containsKey("a"));
Assert.assertTrue(json.getJSONArray("sqs").getJSONObject(0).containsKey("seq")); Assert.assertTrue(json.getJSONArray("sqs").getJSONObject(0).containsKey("seq"));
@ -331,28 +331,28 @@ public class JSONObjectTest {
@Test @Test
public void parseBeanTest2() { public void parseBeanTest2() {
TestBean bean = new TestBean(); final TestBean bean = new TestBean();
bean.setDoubleValue(111.1); bean.setDoubleValue(111.1);
bean.setIntValue(123); bean.setIntValue(123);
bean.setList(CollUtil.newArrayList("a", "b", "c")); bean.setList(CollUtil.newArrayList("a", "b", "c"));
bean.setStrValue("strTest"); bean.setStrValue("strTest");
bean.setTestEnum(TestEnum.TYPE_B); bean.setTestEnum(TestEnum.TYPE_B);
JSONObject json = JSONUtil.parseObj(bean, false); final JSONObject json = JSONUtil.parseObj(bean, false);
// 枚举转换检查 // 枚举转换检查
Assert.assertEquals("TYPE_B", json.get("testEnum")); Assert.assertEquals("TYPE_B", json.get("testEnum"));
TestBean bean2 = json.toBean(TestBean.class); final TestBean bean2 = json.toBean(TestBean.class);
Assert.assertEquals(bean.toString(), bean2.toString()); Assert.assertEquals(bean.toString(), bean2.toString());
} }
@Test @Test
public void parseBeanTest3() { public void parseBeanTest3() {
JSONObject json = JSONUtil.createObj() final JSONObject json = JSONUtil.createObj()
.set("code", 22) .set("code", 22)
.set("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}"); .set("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
JSONBean bean = json.toBean(JSONBean.class); final JSONBean bean = json.toBean(JSONBean.class);
Assert.assertEquals(22, bean.getCode()); Assert.assertEquals(22, bean.getCode());
Assert.assertEquals("abc", bean.getData().getObj("jobId")); Assert.assertEquals("abc", bean.getData().getObj("jobId"));
Assert.assertEquals("http://a.com/a.mp4", bean.getData().getObj("videoUrl")); Assert.assertEquals("http://a.com/a.mp4", bean.getData().getObj("videoUrl"));
@ -360,13 +360,13 @@ public class JSONObjectTest {
@Test @Test
public void beanTransTest() { public void beanTransTest() {
UserA userA = new UserA(); final UserA userA = new UserA();
userA.setA("A user"); userA.setA("A user");
userA.setName("nameTest"); userA.setName("nameTest");
userA.setDate(new Date()); userA.setDate(new Date());
JSONObject userAJson = JSONUtil.parseObj(userA); final JSONObject userAJson = JSONUtil.parseObj(userA);
UserB userB = JSONUtil.toBean(userAJson, UserB.class); final UserB userB = JSONUtil.toBean(userAJson, UserB.class);
Assert.assertEquals(userA.getName(), userB.getName()); Assert.assertEquals(userA.getName(), userB.getName());
Assert.assertEquals(userA.getDate(), userB.getDate()); Assert.assertEquals(userA.getDate(), userB.getDate());
@ -374,63 +374,63 @@ public class JSONObjectTest {
@Test @Test
public void beanTransTest2() { public void beanTransTest2() {
UserA userA = new UserA(); final UserA userA = new UserA();
userA.setA("A user"); userA.setA("A user");
userA.setName("nameTest"); userA.setName("nameTest");
userA.setDate(DateUtil.parse("2018-10-25")); userA.setDate(DateUtil.parse("2018-10-25"));
JSONObject userAJson = JSONUtil.parseObj(userA); final JSONObject userAJson = JSONUtil.parseObj(userA);
// 自定义日期格式 // 自定义日期格式
userAJson.setDateFormat("yyyy-MM-dd"); userAJson.setDateFormat("yyyy-MM-dd");
UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class); final UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class);
Assert.assertEquals(DateUtil.parse("2018-10-25"), bean.getDate()); Assert.assertEquals(DateUtil.parse("2018-10-25"), bean.getDate());
} }
@Test @Test
public void beanTransTest3() { public void beanTransTest3() {
JSONObject userAJson = JSONUtil.createObj() final JSONObject userAJson = JSONUtil.createObj()
.set("a", "AValue") .set("a", "AValue")
.set("name", "nameValue") .set("name", "nameValue")
.set("date", "08:00:00"); .set("date", "08:00:00");
UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class); final UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class);
Assert.assertEquals(DateUtil.today() + " 08:00:00", DateUtil.date(bean.getDate()).toString()); Assert.assertEquals(DateUtil.today() + " 08:00:00", DateUtil.date(bean.getDate()).toString());
} }
@Test @Test
public void parseFromBeanTest() { public void parseFromBeanTest() {
UserA userA = new UserA(); final UserA userA = new UserA();
userA.setA(null); userA.setA(null);
userA.setName("nameTest"); userA.setName("nameTest");
userA.setDate(new Date()); userA.setDate(new Date());
JSONObject userAJson = JSONUtil.parseObj(userA); final JSONObject userAJson = JSONUtil.parseObj(userA);
Assert.assertFalse(userAJson.containsKey("a")); Assert.assertFalse(userAJson.containsKey("a"));
JSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false); final JSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false);
Assert.assertTrue(userAJsonWithNullValue.containsKey("a")); Assert.assertTrue(userAJsonWithNullValue.containsKey("a"));
Assert.assertTrue(userAJsonWithNullValue.containsKey("sqs")); Assert.assertTrue(userAJsonWithNullValue.containsKey("sqs"));
} }
@Test @Test
public void specialCharTest() { public void specialCharTest() {
String json = "{\"pattern\": \"[abc]\b\u2001\", \"pattern2Json\": {\"patternText\": \"[ab]\\b\"}}"; final String json = "{\"pattern\": \"[abc]\b\u2001\", \"pattern2Json\": {\"patternText\": \"[ab]\\b\"}}";
JSONObject obj = JSONUtil.parseObj(json); final JSONObject obj = JSONUtil.parseObj(json);
Assert.assertEquals("[abc]\\b\\u2001", obj.getStrEscaped("pattern")); Assert.assertEquals("[abc]\\b\\u2001", obj.getStrEscaped("pattern"));
Assert.assertEquals("{\"patternText\":\"[ab]\\b\"}", obj.getStrEscaped("pattern2Json")); Assert.assertEquals("{\"patternText\":\"[ab]\\b\"}", obj.getStrEscaped("pattern2Json"));
} }
@Test @Test
public void getStrTest() { public void getStrTest() {
String json = "{\"name\": \"yyb\\nbbb\"}"; final String json = "{\"name\": \"yyb\\nbbb\"}";
JSONObject jsonObject = JSONUtil.parseObj(json); final JSONObject jsonObject = JSONUtil.parseObj(json);
// 没有转义按照默认规则显示 // 没有转义按照默认规则显示
Assert.assertEquals("yyb\nbbb", jsonObject.getStr("name")); Assert.assertEquals("yyb\nbbb", jsonObject.getStr("name"));
// 转义按照字符串显示 // 转义按照字符串显示
Assert.assertEquals("yyb\\nbbb", jsonObject.getStrEscaped("name")); Assert.assertEquals("yyb\\nbbb", jsonObject.getStrEscaped("name"));
String bbb = jsonObject.getStr("bbb", "defaultBBB"); final String bbb = jsonObject.getStr("bbb", "defaultBBB");
Assert.assertEquals("defaultBBB", bbb); Assert.assertEquals("defaultBBB", bbb);
} }
@ -444,7 +444,7 @@ public class JSONObjectTest {
Assert.assertEquals("张三", jsonObject.getStr("name")); Assert.assertEquals("张三", jsonObject.getStr("name"));
Assert.assertEquals(new Integer(35), jsonObject.getInt("age")); Assert.assertEquals(new Integer(35), jsonObject.getInt("age"));
JSONObject json = JSONUtil.createObj() final JSONObject json = JSONUtil.createObj()
.set("name", "张三") .set("name", "张三")
.set("age", 35); .set("age", 35);
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class); final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
@ -454,10 +454,10 @@ public class JSONObjectTest {
@Test @Test
public void setDateFormatTest() { public void setDateFormatTest() {
JSONConfig jsonConfig = JSONConfig.create(); final JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
JSONObject json = new JSONObject(jsonConfig); final JSONObject json = new JSONObject(jsonConfig);
json.append("date", DateUtil.parse("2020-06-05 11:16:11")); json.append("date", DateUtil.parse("2020-06-05 11:16:11"));
json.append("bbb", "222"); json.append("bbb", "222");
json.append("aaa", "123"); json.append("aaa", "123");
@ -466,16 +466,16 @@ public class JSONObjectTest {
@Test @Test
public void setDateFormatTest2() { public void setDateFormatTest2() {
JSONConfig jsonConfig = JSONConfig.create(); final JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("yyyy#MM#dd"); jsonConfig.setDateFormat("yyyy#MM#dd");
Date date = DateUtil.parse("2020-06-05 11:16:11"); final Date date = DateUtil.parse("2020-06-05 11:16:11");
JSONObject json = new JSONObject(jsonConfig); final JSONObject json = new JSONObject(jsonConfig);
json.set("date", date); json.set("date", date);
json.set("bbb", "222"); json.set("bbb", "222");
json.set("aaa", "123"); json.set("aaa", "123");
String jsonStr = "{\"date\":\"2020#06#05\",\"bbb\":\"222\",\"aaa\":\"123\"}"; final String jsonStr = "{\"date\":\"2020#06#05\",\"bbb\":\"222\",\"aaa\":\"123\"}";
Assert.assertEquals(jsonStr, json.toString()); Assert.assertEquals(jsonStr, json.toString());
@ -486,16 +486,16 @@ public class JSONObjectTest {
@Test @Test
public void setCustomDateFormatTest() { public void setCustomDateFormatTest() {
JSONConfig jsonConfig = JSONConfig.create(); final JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("#sss"); jsonConfig.setDateFormat("#sss");
Date date = DateUtil.parse("2020-06-05 11:16:11"); final Date date = DateUtil.parse("2020-06-05 11:16:11");
JSONObject json = new JSONObject(jsonConfig); final JSONObject json = new JSONObject(jsonConfig);
json.set("date", date); json.set("date", date);
json.set("bbb", "222"); json.set("bbb", "222");
json.set("aaa", "123"); json.set("aaa", "123");
String jsonStr = "{\"date\":1591326971,\"bbb\":\"222\",\"aaa\":\"123\"}"; final String jsonStr = "{\"date\":1591326971,\"bbb\":\"222\",\"aaa\":\"123\"}";
Assert.assertEquals(jsonStr, json.toString()); Assert.assertEquals(jsonStr, json.toString());
@ -506,7 +506,7 @@ public class JSONObjectTest {
@Test @Test
public void getTimestampTest() { public void getTimestampTest() {
String timeStr = "1970-01-01 00:00:00"; final String timeStr = "1970-01-01 00:00:00";
final JSONObject jsonObject = JSONUtil.createObj().set("time", timeStr); final JSONObject jsonObject = JSONUtil.createObj().set("time", timeStr);
final Timestamp time = jsonObject.get("time", Timestamp.class); final Timestamp time = jsonObject.get("time", Timestamp.class);
Assert.assertEquals("1970-01-01 00:00:00.0", time.toString()); Assert.assertEquals("1970-01-01 00:00:00.0", time.toString());
@ -605,7 +605,7 @@ public class JSONObjectTest {
@Test @Test
public void floatTest() { public void floatTest() {
Map<String, Object> map = new HashMap<>(); final Map<String, Object> map = new HashMap<>();
map.put("c", 2.0F); map.put("c", 2.0F);
final String s = JSONUtil.toJsonStr(map); final String s = JSONUtil.toJsonStr(map);
@ -626,7 +626,7 @@ public class JSONObjectTest {
@Test @Test
public void putByPathTest() { public void putByPathTest() {
JSONObject json = new JSONObject(); final JSONObject json = new JSONObject();
json.putByPath("aa.bb", "BB"); json.putByPath("aa.bb", "BB");
Assert.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString()); Assert.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString());
} }
@ -634,8 +634,8 @@ public class JSONObjectTest {
@Test @Test
public void bigDecimalTest() { public void bigDecimalTest() {
String jsonStr = "{\"orderId\":\"1704747698891333662002277\"}"; final String jsonStr = "{\"orderId\":\"1704747698891333662002277\"}";
BigDecimalBean bigDecimalBean = JSONUtil.toBean(jsonStr, BigDecimalBean.class); final BigDecimalBean bigDecimalBean = JSONUtil.toBean(jsonStr, BigDecimalBean.class);
Assert.assertEquals("{\"orderId\":1704747698891333662002277}", JSONUtil.toJsonStr(bigDecimalBean)); Assert.assertEquals("{\"orderId\":1704747698891333662002277}", JSONUtil.toJsonStr(bigDecimalBean));
} }
@ -647,7 +647,7 @@ public class JSONObjectTest {
@Test @Test
public void filterIncludeTest() { public void filterIncludeTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create()) final JSONObject json1 = JSONUtil.createObj(JSONConfig.create())
.set("a", "value1") .set("a", "value1")
.set("b", "value2") .set("b", "value2")
.set("c", "value3") .set("c", "value3")
@ -659,7 +659,7 @@ public class JSONObjectTest {
@Test @Test
public void filterExcludeTest() { public void filterExcludeTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create()) final JSONObject json1 = JSONUtil.createObj(JSONConfig.create())
.set("a", "value1") .set("a", "value1")
.set("b", "value2") .set("b", "value2")
.set("c", "value3") .set("c", "value3")
@ -671,7 +671,7 @@ public class JSONObjectTest {
@Test @Test
public void editTest() { public void editTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create()) final JSONObject json1 = JSONUtil.createObj(JSONConfig.create())
.set("a", "value1") .set("a", "value1")
.set("b", "value2") .set("b", "value2")
.set("c", "value3") .set("c", "value3")
@ -691,7 +691,7 @@ public class JSONObjectTest {
@Test @Test
public void toUnderLineCaseTest() { public void toUnderLineCaseTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create()) final JSONObject json1 = JSONUtil.createObj(JSONConfig.create())
.set("aKey", "value1") .set("aKey", "value1")
.set("bJob", "value2") .set("bJob", "value2")
.set("cGood", "value3") .set("cGood", "value3")
@ -706,7 +706,7 @@ public class JSONObjectTest {
@Test @Test
public void nullToEmptyTest() { public void nullToEmptyTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setIgnoreNullValue(false)) final JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setIgnoreNullValue(false))
.set("a", null) .set("a", null)
.set("b", "value2"); .set("b", "value2");
@ -719,18 +719,18 @@ public class JSONObjectTest {
@Test @Test
public void parseFilterTest() { public void parseFilterTest() {
String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}"; final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> "b".equals(pair.getKey())); final JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> "b".equals(pair.getKey()));
Assert.assertEquals(1, jsonObject.size()); Assert.assertEquals(1, jsonObject.size());
Assert.assertEquals("value2", jsonObject.get("b")); Assert.assertEquals("value2", jsonObject.get("b"));
} }
@Test @Test
public void parseFilterEditTest() { public void parseFilterEditTest() {
String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}"; final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
//noinspection MismatchedQueryAndUpdateOfCollection //noinspection MismatchedQueryAndUpdateOfCollection
JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> { final JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> {
if("b".equals(pair.getKey())){ if("b".equals(pair.getKey())){
pair.setValue(pair.getValue() + "_edit"); pair.setValue(pair.getValue() + "_edit");
} }