JSON.parseObject强制将自动转化的Intage型设置为Long型

2024-01-02 05:46:59

通过Redis或Caffeine存储入json型String,通过JSON.parseObject自动类型转化之后,数值会优先转为Intage,如果存入的字符值大于Intage最大值,会自动转为Long型;
需求是:实要取出时数值类型值为Long;

1、写入Caffeine缓存
    public static void put(String key, Map val) {
        cache.put(key, JSONObject.toJSONString(val));
    }
2、获取Caffeine缓存
    public static Optional<Map> get(String key) {
        String value = cache.getIfPresent(key);
        Map maps = JSON.parseObject(value, Map.class);
        return Optional.ofNullable(maps);
    }
3、解决方法

在获取缓存时,使用TypeReference强制将存储转为指定类型;

Map maps = JSON.parseObject(value, new TypeReference<Map<Long, String>>() {}, Feature.InitStringFieldAsEmpty);
4、完整样例

CaffeineUtil.java

public class CaffeineUtil {

    public static Cache<String, String> cache = Caffeine.newBuilder()
            .initialCapacity(800)
            .maximumSize(2000)
            .expireAfterWrite(Duration.ofMinutes(60))
            .build();


    public static Optional<Map> get(String key) {
        String value = cache.getIfPresent(key);
        //会将存入的Map中Long对象自动转化为Integer型
        //但如果值超出了Integer的最大值,会自动转为Long型
        //Map maps = JSON.parseObject(value, Map.class);

        //强制将存储转为Map<Long, String>
        Map maps = JSON.parseObject(value, new TypeReference<Map<Long, String>>() {}, Feature.InitStringFieldAsEmpty);

        return Optional.ofNullable(maps);
    }


    public static void put(String key, Map val) {
        cache.put(key, JSONObject.toJSONString(val));
    }
}

TestCaffeineController.java

public class TestCaffeineController {

    @RequestMapping("/testCaffeine")
    public Object testCaffeine(Long userId){
        String userImg = this.getCacheData(userId);
        return "获取到的userImg:"+userImg;
    }


    public String getCacheData(Long userId){
        Map<Long, String> UserMaps = new HashMap<>();
        String cacheKey = userId+"_key";
        Optional<Map> cacheUserMaps =  CaffeineUtil.get(cacheKey);
        if(cacheUserMaps.isPresent()){
            UserMaps = cacheUserMaps.get();
        }else{
            JSONArray userArray = new JSONArray();
            JSONObject object1= new JSONObject();
            object1.put("id", 1l);
            object1.put("imgUrl", "aaaaaaa");
            JSONObject object2= new JSONObject();
            //因为该值已经超过Intage型最大值,在从缓存中取出时会自动转成Long类型
            object2.put("id", 234567899999l);
            object2.put("imgUrl", "bbbbbbb");
            userArray.add(object1);
            userArray.add(object2);

            if(CollectionUtils.isNotEmpty(userArray)){
                UserMaps = userArray.stream().collect(Collectors.toMap(o -> ((JSONObject)o).getLong("id"), o -> ((JSONObject)o).getString("imgUrl")));
                CaffeineUtil.put(cacheKey, UserMaps);
            }
        }

        //如果从缓存中取的UserMaps类型为Integer型,这里将匹配不到
        if(UserMaps.containsKey(userId)) {
            System.out.println("存在该值.");
            return UserMaps.get(userId);
        }else{
            System.out.println("不存在该值.");
        }
        return null;
    }
}

文章来源:https://blog.csdn.net/xianglingchuan/article/details/135330719
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。