匿名内部类实现TypeReference

阅读 54

2022-01-05

@Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //  1. 加入缓存逻辑, 缓存中存的数据是JSON字符串
        //  JSON跨语言,跨平台兼容
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 2. 缓存中没有, 查询数据库
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            //  3. 查到的数据再放入缓存, 将对象转为JSON放入缓存
            String s = JSON.toJSONString(catalogJsonFromDB);
            stringRedisTemplate.opsForValue().set("catalogJSON", s);
            return catalogJsonFromDB;
        }
//   匿名内部类, TypeReference的构造器是protected修饰的,不能被包外的类实例化,所以需要写一个实现类
        Map<String, List<Catalog2Vo>> result =
                JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        }); 
        return result;
    }

精彩评论(0)

0 0 举报