feature: json的getByPath方法新增更为通用的指定出参类型重载

This commit is contained in:
TomShiDi
2024-12-08 15:41:43 +08:00
parent fe567de38d
commit 5622f5e7a7
4 changed files with 67 additions and 4 deletions

View File

@@ -1,8 +1,12 @@
package cn.hutool.json;
import static org.junit.jupiter.api.Assertions.*;
import cn.hutool.core.lang.TypeReference;
import org.junit.jupiter.api.Test;
import java.util.List;
/**
* JSON路径单元测试
*
@@ -27,4 +31,23 @@ public class JSONPathTest {
Long accountId = JSONUtil.getByPath(json, "$.accountId", 0L);
assertEquals(111L, accountId.longValue());
}
@Test
public void getByPathTest3(){
String str = "[{'accountId':1},{'accountId':2},{'accountId':3}]";
JSON json = JSONUtil.parse(str);
// 返回指定泛型的对象 List<Long>
List<Long> accountIds = json.getByPath("$.accountId", new TypeReference<List<Long>>() {
});
assertNotNull(accountIds);
assertArrayEquals(new Long[]{1L, 2L, 3L}, accountIds.toArray());
str = "{\"accountInfos\": [{\"accountId\":1},{\"accountId\":2},{\"accountId\":3}]}";
json = JSONUtil.parse(str);
// 返回指定泛型的对象 List<Long>
accountIds = json.getByPath("$.accountInfos.accountId", new TypeReference<List<Long>>() {
});
assertNotNull(accountIds);
assertArrayEquals(new Long[]{1L, 2L, 3L}, accountIds.toArray());
}
}