This commit is contained in:
Looly
2021-03-18 21:16:14 +08:00
parent 825b5ea1b4
commit abdedf6822
9 changed files with 86 additions and 6 deletions

View File

@@ -543,7 +543,7 @@ public class JSONUtil {
* @see JSON#getByPath(String)
*/
public static Object getByPath(JSON json, String expression) {
return (null == json || StrUtil.isBlank(expression)) ? null : json.getByPath(expression);
return getByPath(json, expression, null);
}
/**
@@ -572,7 +572,15 @@ public class JSONUtil {
*/
@SuppressWarnings("unchecked")
public static <T> T getByPath(JSON json, String expression, T defaultValue) {
return (T) ObjectUtil.defaultIfNull(getByPath(json, expression), defaultValue);
if((null == json || StrUtil.isBlank(expression))){
return defaultValue;
}
if(null != defaultValue){
final Class<T> type = (Class<T>) defaultValue.getClass();
return ObjectUtil.defaultIfNull(json.getByPath(expression, type), defaultValue);
}
return (T) json.getByPath(expression);
}
/**

View File

@@ -0,0 +1,27 @@
package cn.hutool.json;
import cn.hutool.core.bean.BeanUtil;
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
import java.time.LocalDateTime;
/**
* 测试带毫秒的日期转换
*/
public class IssueI3BS4S {
@Test
public void toBeanTest(){
String jsonStr = "{date: '2021-03-17T06:31:33.99'}";
final Bean1 bean1 = new Bean1();
BeanUtil.copyProperties(JSONUtil.parseObj(jsonStr), bean1);
Assert.assertEquals("2021-03-17T06:31:33.099", bean1.getDate().toString());
}
@Data
public static class Bean1{
private LocalDateTime date;
}
}

View File

@@ -5,7 +5,7 @@ import org.junit.Test;
/**
* JSON路径单元测试
*
*
* @author looly
*
*/
@@ -19,4 +19,12 @@ public class JSONPathTest {
value = JSONUtil.parseArray(json).getByPath("[1].name");
Assert.assertEquals("mingzi", value);
}
@Test
public void getByPathTest2(){
String str = "{'accountId':111}";
JSON json = JSONUtil.parse(str);
Long accountId = JSONUtil.getByPath(json, "$.accountId", 0L);
Assert.assertEquals(111L, accountId.longValue());
}
}