jackson 反序列化复杂泛型对象

最近在使用Redis 缓存数据的时候使用的spring 的aop自动从缓存中去区json数据。发现方法的返回值带有泛型时,直接简单的调用使用下面的方法无法拿到正确的结果。
 Method method = ((MethodSignature) pjp.getSignature()).getMethod();
Object[] args = pjp.getArgs();
//根据方法注解和参数获取缓存的key, 
String key = GenerateKeyUtil.getCacheKey(method, args); 

String cacheJson = redisTemplate.opsForValue().get(key);

 Class returnType = method.getReturnType();

 return objctMapper.readValue(cacheJson,returnType);

如果method的返回类型是List,上面的方法method.getReturnType() 的返回值只是Class,所以反序列化的结果是ArrayList类型的,而并不是List类型。另外,上面为了简化代码没有判断缓存是否有值,和没有缓存执行目标方法的并添加缓存的代码。

后来看了一下jackson的代码注释,使用下列方法可以通用的解析json数据为带泛型的结果;


 
  
Method method = ((MethodSignature) pjp.getSignature()).getMethod();

 Object[] args = pjp.getArgs();
//根据方法注解和参数获取缓存的key,
 String key = GenerateKeyUtil.getCacheKey(method, args);
//获取redis缓存的值,
 String cacheJson = redisTemplate.opsForValue().get(key);    
 //带有泛型信息
 Type genericReturnType = method.getGenericReturnType(); 
 //获取返回类的绑定信息    
JavaType javaType = JsonUtil.getJavaType(genericReturnType);   
 
return objectMapper.readValue(cacheJson,javaType);
  

下面是JsonUtil.getJavaType(Type type)的代码

 public static JavaType getJavaType(Type type) {
        //判断是否带有泛型
        if (type instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
            //获取泛型类型
            Class rowClass = (Class) ((ParameterizedType) type).getRawType();
            
            JavaType[] javaTypes = new JavaType[actualTypeArguments.length];
            
            for (int i = 0; i < actualTypeArguments.length; i++) {
                //泛型也可能带有泛型,递归获取
                javaTypes[i] = getJavaType(actualTypeArguments[i]);
            }
            return TypeFactory.defaultInstance().constructParametricType(rowClass, javaTypes);
        } else {
            //简单类型直接用该类构建JavaType
            Class cla = (Class) type;
            return TypeFactory.defaultInstance().constructParametricType(cla, new JavaType[0]);
        }
    }

上面的方法经过测试可以解析任意层数,但是是递归实现,搞了半天没搞出来循环方式实现。

有循环实现的求评论个链接或则代码。。。

另外把TypeFactory.constructParametricType()的源码注释贴下面

 /**
     * Factory method for constructing {@link JavaType} that
     * represents a parameterized type. For example, to represent
     * type List>, you could
     * call
     *
     *  JavaType inner = TypeFactory.constructParametricType(Set.class, Set.class, Integer.class);
     *  return TypeFactory.constructParametricType(ArrayList.class, List.class, inner);
     *
*

* The reason for first two arguments to be separate is that parameterization may * apply to a super-type. For example, if generic type was instead to be * constructed for ArrayList, the usual call would be: *

     *  TypeFactory.constructParametricType(ArrayList.class, List.class, Integer.class);
     *
* since parameterization is applied to {@link java.util.List}. * In most cases distinction does not matter, but there are types where it does; * one such example is parameterization of types that implement {@link java.util.Iterator}. *

* NOTE: type modifiers are NOT called on constructed type. * * @param rawType Actual type-erased type * @param parameterTypes Type parameters to apply * * @since 2.5 NOTE: was briefly deprecated for 2.6 */

觉得有用点个赞。

你可能感兴趣的:(java,java,json,jackson)