package com.rzyc.provinceUtil; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * @author dong * @date 2025-03-18 15:25 * @Version V1.0 */ public class JsonUtils { private static final ObjectMapper objectMapper = new ObjectMapper(); /** * 将 JSON 字符串转换为包含泛型的对象 * @param json JSON 字符串 * @param mainClass 主类型(如 Result.class) * @param subClass 泛型参数类型(如 User.class) * @return 转换后的对象 */ public static T fromJson(String json, Class mainClass, Class subClass) { try { // 动态构建泛型类型(例如 Result) Type type = createParametricType(mainClass, subClass); return objectMapper.readValue(json, new TypeReference() { @Override public Type getType() { return type; } }); } catch (Exception e) { throw new RuntimeException("JSON 转换失败", e); } } /** * 构建 ParameterizedType(例如 Result) */ private static ParameterizedType createParametricType(final Class rawType, final Type... typeArguments){ return new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return typeArguments; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } }; } /** * 使用示例:解析 Result> * @version v1.0 * @author dong * @date 2025/3/18 15:44 */ /* Type userListType = new TypeToken>() {}.getType(); Result> result = JsonUtils.fromJsonComplex( json, Result.class, userListType );*/ /** * json转list * @version v1.0 * @author dong * @date 2025/3/18 15:43 */ public static T fromJsonComplex(String json, Class rawType, Type... genericTypes) { try { ParameterizedType type = new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return genericTypes; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } }; return objectMapper.readValue(json, new TypeReference() { @Override public Type getType() { return type; } }); } catch (Exception e) { throw new RuntimeException("JSON 转换失败", e); } } }