diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/JsonUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/JsonUtil.java index dce9a241ee13a1082abeb5bec74037fd5929c94f..56da985a84a14dc8678eb8ed61b05b8e609459a5 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/JsonUtil.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/JsonUtil.java @@ -1,6 +1,5 @@ package com.central.common.utils; - import com.central.common.constant.CommonConstant; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; @@ -85,7 +84,7 @@ public class JsonUtil { } /** - * 字符串转换为自定义对象 + * 字符串转换为指定对象 * @param json json字符串 * @param cls 目标对象 */ @@ -101,7 +100,26 @@ public class JsonUtil { } /** - * 字符串转换为自定义对象 + * 字符串转换为指定对象,并增加泛型转义 + * 例如:List test = toObject(jsonStr, List.class, Integer.class); + * @param json json字符串 + * @param parametrized 目标对象 + * @param parameterClasses 泛型对象 + */ + public static T toObject(String json, Class parametrized, Class... parameterClasses) { + if(StringUtils.isBlank(json) || parametrized == null){ + return null; + } + try { + JavaType javaType = MAPPER.getTypeFactory().constructParametricType(parametrized, parameterClasses); + return MAPPER.readValue(json, javaType); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * 字符串转换为指定对象 * @param json json字符串 * @param typeReference 目标对象类型 */ @@ -146,7 +164,7 @@ public class JsonUtil { } /** - * 字符串转换为list对象 + * json字符串转换为list对象 * @param json json字符串 */ public static List toList(String json) { @@ -161,7 +179,7 @@ public class JsonUtil { } /** - * json字符串转换为list + * json字符串转换为list对象,并指定元素类型 * @param json json字符串 * @param cls list的元素类型 */