ganzi-api/inventory-dao/src/main/java/com/rzyc/provinceUtil/JsonUtils.java
2025-03-18 17:31:01 +08:00

117 lines
3.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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, R> T fromJson(String json, Class<T> mainClass, Class<R> subClass) {
try {
// 动态构建泛型类型(例如 Result<User>
Type type = createParametricType(mainClass, subClass);
return objectMapper.readValue(json, new TypeReference<T>() {
@Override
public Type getType() {
return type;
}
});
} catch (Exception e) {
throw new RuntimeException("JSON 转换失败", e);
}
}
/**
* 构建 ParameterizedType例如 Result<User>
*/
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<List<User>>
* @version v1.0
* @author dong
* @date 2025/3/18 15:44
*/
/* Type userListType = new TypeToken<List<User>>() {}.getType();
Result<List<User>> result = JsonUtils.fromJsonComplex(
json,
Result.class,
userListType
);*/
/**
* json转list
* @version v1.0
* @author dong
* @date 2025/3/18 15:43
*/
public static <T> 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<T>() {
@Override
public Type getType() {
return type;
}
});
} catch (Exception e) {
throw new RuntimeException("JSON 转换失败", e);
}
}
}