mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
add converter for json
This commit is contained in:
@@ -7,6 +7,7 @@ import cn.hutool.core.convert.impl.DateConverter;
|
||||
import cn.hutool.core.convert.impl.TemporalAccessorConverter;
|
||||
import cn.hutool.core.reflect.TypeUtil;
|
||||
import cn.hutool.core.text.StrUtil;
|
||||
import cn.hutool.json.convert.JSONConverter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.temporal.TemporalAccessor;
|
||||
@@ -59,6 +60,12 @@ public class JSONConfig implements Serializable {
|
||||
*/
|
||||
private Converter converter = (type, value)->{
|
||||
final Class<?> rawType = TypeUtil.getClass(type);
|
||||
if(null == rawType){
|
||||
return value;
|
||||
}
|
||||
if(JSON.class.isAssignableFrom(rawType)){
|
||||
return JSONConverter.INSTANCE.toJSON(value);
|
||||
}
|
||||
if(Date.class.isAssignableFrom(rawType) || TemporalAccessor.class.isAssignableFrom(rawType)){
|
||||
// 用户指定了日期格式,获取日期属性时使用对应格式
|
||||
final String valueStr = Convert.convertWithCheck(String.class, value, null, isIgnoreError());
|
||||
|
@@ -4,6 +4,7 @@ import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.bean.copier.BeanCopier;
|
||||
import cn.hutool.core.convert.ConvertException;
|
||||
import cn.hutool.core.convert.Converter;
|
||||
import cn.hutool.core.convert.RegisterConverter;
|
||||
import cn.hutool.core.convert.impl.ArrayConverter;
|
||||
import cn.hutool.core.convert.impl.CollectionConverter;
|
||||
import cn.hutool.core.convert.impl.MapConverter;
|
||||
@@ -42,6 +43,11 @@ import java.util.Map;
|
||||
public class JSONConverter implements Converter {
|
||||
public static final JSONConverter INSTANCE = new JSONConverter(null);
|
||||
|
||||
static {
|
||||
RegisterConverter.getInstance().putCustom(JSONObject.class, INSTANCE);
|
||||
RegisterConverter.getInstance().putCustom(JSONArray.class, INSTANCE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建JSON转换器
|
||||
*
|
||||
@@ -141,6 +147,12 @@ public class JSONConverter implements Converter {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 标准转换器
|
||||
final Converter converter = RegisterConverter.getInstance().getConverter(targetType, true);
|
||||
if (null != converter) {
|
||||
return (T) converter.convert(targetType, json);
|
||||
}
|
||||
|
||||
// 尝试转Bean
|
||||
if (BeanUtil.isBean(rawType)) {
|
||||
return BeanCopier.of(json,
|
||||
|
2
hutool-json/src/test/java/Issue2555Test.java → hutool-json/src/test/java/cn/hutool/json/Issue2555Test.java
Executable file → Normal file
2
hutool-json/src/test/java/Issue2555Test.java → hutool-json/src/test/java/cn/hutool/json/Issue2555Test.java
Executable file → Normal file
@@ -1,3 +1,5 @@
|
||||
package cn.hutool.json;
|
||||
|
||||
import cn.hutool.json.JSON;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
Reference in New Issue
Block a user