本文主要是介绍JSON.parseObject强制将自动转化的Intage型设置为Long型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通过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;}
}
这篇关于JSON.parseObject强制将自动转化的Intage型设置为Long型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!