fastjson使用TypeReference反序列化2层以上嵌套泛型类

1.序列化BaseResult
实际对象为BaseResult ,该类型为嵌套一层的泛型,以下转换可以成功

String responseStr = "{\"code\":\"200\",\"msg\":\"success\",\"data\":{\"item\":0}}";
TypeReference< BaseResult<T>> type = new TypeReference<BaseResult<T>>(Item.class) { };
BaseResult<T> baseResult = JSON.parseObject(responseStr, type );

2.序列化BaseResult<List>,该类型为嵌套两层的泛型,使用TypeReference构造泛型会报错,需要使用以下方式构造Type

 /** 为序列化两次以上泛型提供的工具类 BaseResult<List<T>>,作用类似
 * TypeReference< BaseResult<List<T>>> type = new TypeReference<BaseResult<List<T>>>(BaseResult.class, List.class, returnClazz) { };
 * @param types
 * @return
 */
public static Type buildType(Type... types) {
    ParameterizedTypeImpl beforeType = null;
    if (types != null && types.length > 0) {
        for (int i = types.length - 1; i > 0; i--) {
            beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
        }
    }
    return beforeType;
}

使用:

String responseStr = "{\"code\":\"200\",\"msg\":\"success\",\"data\":[{\"item\":0}]}";
BaseResult<List<T>> baseResult = JSON.parseObject(responseStr, ReflectUtil.buildType(BaseResult.class, List.class, Item.class));

3.泛型类中根据this.class获取真实类型并序列化2层以上嵌套类型
如:

public class ItemClass extends AbstractItemClass<Item> {
		
		BaseResult<List<T>> getItem (String responseStr) {
		 // 获取泛型类中的真实类型 Item.class
			Class<T> returnClazz = ReflectUtil.deSerializableClazz(this.getClass());
			BaseResult<List<T>> baseResult = JSON.parseObject(responseStr, ReflectUtil.buildType(BaseResult.class, List.class, returnClazz));
		}
}
/**
 * 获取泛型类中的真实类型 AreaNumTPDataVO
 * AbstractItemClass<Item>
 * @param clazz
 * @param <T>
 * @return
 */
public static <T> Class<T> deSerializableClazz(Class clazz) {
    Type type = clazz.getGenericSuperclass();
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        System.out.println(parameterizedType.getActualTypeArguments()[0]);
        return (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }
    throw new RuntimeException();
}

最后附一张关系图
在这里插入图片描述

参考:
fastjson反序列化多层嵌套泛型类与java中的Type类型
打个赌你可能不知道如何获取Java泛型的Class对象
Java如何优雅获取泛型类型

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用fastjson进行泛型类反序列化,你可以按照以下步骤进行操作: 首先,确保你已经引入了fastjson的依赖,可以通过Maven等构建工具添加以下依赖项: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.79</version> </dependency> ``` 接下来,假设你有一个泛型类`Result<T>`,如下所示: ```java import com.alibaba.fastjson.JSON; public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } public static <T> Result<T> fromJson(String json, Class<T> clazz) { return JSON.parseObject(json, new TypeReference<Result<T>>(clazz) {}.getType()); } } ``` 在上述代码中,`fromJSON`方法使用fastjson的`parseObject`方法将JSON字符串反序列化为`Result<T>`对象。 然后,你可以使用以下代码将JSON字符串反序列化为具体的泛型类对象: ```java import com.alibaba.fastjson.JSON; public class Main { public static void main(String[] args) { String json = "{\"code\":200,\"message\":\"Success\",\"data\":{\"name\":\"John\",\"age\":25}}"; Result<User> result = Result.fromJson(json, User.class); System.out.println("Code: " + result.getCode()); System.out.println("Message: " + result.getMessage()); User user = result.getData(); System.out.println("Name: " + user.getName()); System.out.println("Age: " + user.getAge()); } } ``` 在上述代码中,我们将一个包含`User`对象的JSON字符串反序列化为`Result<User>`对象,并输出其中的字段值。 请注意,为了正确反序列化泛型类,我们需要通过传递`Class<T>`参数给`fromJSON`方法来指定具体的泛型类型。 以上就是使用fastjson进行泛型类反序列化的基本示例。当然,根据实际需求和数据结构的复杂程度,你可能需要进行更多的定制和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值