JAVA基础之HashMap转List

Love The Way You Lie 2022-05-22 01:53 538阅读 0赞

前言

今天在开发中,用elasticsearch + java实现热门关键字搜索商品列表这样一个功能。。。惊恐遇到一个HashMap强转List失败问题。这里记录一下~大笑

调用接口

这里我先用postman调了一下通过热门关键字查询商品列表接口

20180612211106994

发现500,服务器内部错误了。。。what?因为es在阿里云服务器上面,本地又不能打断点,debug调试。查看服务器日志,找到问题所在;

服务器日志

问题所在如下图:

20180612210709100

噢~~~HashMap转强转List失败了。

发现问题

查看了日志,再看了看代码。

  1. @Override
  2. public Map<String, Object> handleEsGoodsVipPrice(Integer uId, Map<String, Object> map) {
  3. Map<String, Object> vipUser = vipUserMapper.queryUserVipInfoByUserId(uId);
  4. // es查询结果得到Map,map中取到esGoods,转为list,处理数据后返回
  5. List<EsGoods> list = (List<EsGoods>) map.get("esGoods");
  6. if (vipUser != null) {
  7. // 用户有Vip等级
  8. // 根据userID得到用户vip等级ID
  9. Integer gradeId = (Integer) vipUser.get("gradeId");
  10. list.forEach(bsGoodsRecommendH5 -> {
  11. BsGoodsVipPrice goodsVipPrice = goodsVipPriceMapper.queryVipPricesByGoodsIdAndVipId(bsGoodsRecommendH5.getGoodsId(), gradeId);
  12. if (goodsVipPrice != null && goodsVipPrice.getVipPrice() != null) {
  13. bsGoodsRecommendH5.setVipPrice(goodsVipPrice.getVipPrice());
  14. } else {
  15. //如果没查到该用户对应vip等级的vip价格 取最低Vip等级的vip价格
  16. Long defaultVipPrice = goodsVipPriceMapper.queryDefaultVipPriceByGoodsId(bsGoodsRecommendH5.getGoodsId());
  17. bsGoodsRecommendH5.setVipPrice(defaultVipPrice);
  18. }
  19. });
  20. } else {
  21. // 用户没有vip等级 vip价格默认取最低等级对应的价格
  22. list.forEach(bsGoodsRecommendH5 -> {
  23. Long defaultVipPrice = goodsVipPriceMapper.queryDefaultVipPriceByGoodsId(bsGoodsRecommendH5.getGoodsId());
  24. bsGoodsRecommendH5.setVipPrice(defaultVipPrice);
  25. });
  26. }
  27. map.put("esGoods", list);
  28. return map;
  29. }

原来就是这里强转出了问题

  1. List<EsGoods> list = (List<EsGoods>) map.get("esGoods");

解决方法

呵~~既然hashMap强转list失败了,我就不强转了。先把hashMap先转为json字符串,然后将得到的json字符串转为list就ok了!!!

代码如下:生气

  1. //将map.get("esGoods")先转为json字符串,然后将得到的json字符串转为list就ok了!!!
  2. List<EsGoods> list = JsonUtils.json2ListBean(JsonUtils.toJson(map.get("esGoods")), EsGoods.class);

总结

map不能转list??因为开发时间比较紧,日后再带着这个问题,去寻找答案吧

附上json工具类
  1. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  2. import com.fasterxml.jackson.core.JsonFactory;
  3. import com.fasterxml.jackson.core.JsonGenerator;
  4. import com.fasterxml.jackson.core.JsonParser.Feature;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.wybc.common.exception.BusiException;
  8. import com.wybc.common.model.E;
  9. import net.sf.json.JSONArray;
  10. import java.beans.BeanInfo;
  11. import java.beans.Introspector;
  12. import java.beans.PropertyDescriptor;
  13. import java.io.IOException;
  14. import java.io.StringWriter;
  15. import java.lang.reflect.Method;
  16. import java.util.*;
  17. /**
  18. * Json工具类
  19. */
  20. public class JsonUtils {
  21. private static final ObjectMapper mapper = new ObjectMapper();
  22. static {
  23. mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  24. mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  25. mapper.setSerializationInclusion(Include.NON_NULL);
  26. }
  27. private JsonUtils() {
  28. }
  29. /**
  30. * json字符串转换为类
  31. */
  32. public static <T> T toBean(String json, Class<T> clazz) {
  33. try {
  34. T bean = (T) mapper.readValue(json, clazz);
  35. return bean;
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
  41. @SuppressWarnings("unchecked")
  42. public static HashMap<String, Object> toBean(String json) {
  43. return toBean(json, HashMap.class);
  44. }
  45. @SuppressWarnings("unchecked")
  46. public static HashMap<String,String> toBeanStr(String json) {
  47. return toBean(json, HashMap.class);
  48. }
  49. @SuppressWarnings("unchecked")
  50. public static <T> T toBean(String json, TypeReference<T> tr){
  51. try {
  52. T bean = (T) mapper.readValue(json, tr);
  53. return bean;
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. }
  57. return null;
  58. }
  59. /**
  60. * 对象转换为json字符串
  61. */
  62. public static String toJson(Object bean) {
  63. String json = null;
  64. JsonGenerator gen = null;
  65. StringWriter sw = new StringWriter();
  66. try {
  67. gen = new JsonFactory().createGenerator(sw);
  68. mapper.writeValue(gen, bean);
  69. json = sw.toString();
  70. } catch (IOException e) {
  71. throw new BusiException(E.SYSTEM_ERROR);
  72. } finally {
  73. try {
  74. if (gen != null) {
  75. gen.close();
  76. }
  77. if (sw != null) {
  78. sw.close();
  79. }
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. return json;
  85. }
  86. @SuppressWarnings("unchecked")
  87. public static List<Object> toList(String json) {
  88. return toBean(json, ArrayList.class);
  89. }
  90. /**
  91. * 对象转换为Map
  92. */
  93. public static Map<String, Object> transBean2Map(Object obj) {
  94. if (obj == null) {
  95. return null;
  96. }
  97. Map<String, Object> map = new HashMap<String, Object>();
  98. try {
  99. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  100. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  101. for (PropertyDescriptor property : propertyDescriptors) {
  102. String key = property.getName();
  103. if (!key.equals("class")) {
  104. Method getter = property.getReadMethod();
  105. Object value = getter.invoke(obj);
  106. map.put(key, value);
  107. }
  108. }
  109. } catch (Exception e) {
  110. System.out.println("transBean2Map Error " + e);
  111. }
  112. return map;
  113. }
  114. /**
  115. * json字符串转换为List
  116. */
  117. public static <T> List<T>json2ListBean(String json,Class<T>cls){
  118. JSONArray jArray= JSONArray.fromObject(json);
  119. Collection<T> collection = JSONArray.toCollection(jArray, cls);
  120. List<T> list = new ArrayList<T>();
  121. Iterator<T> it = collection.iterator();
  122. while (it.hasNext()) {
  123. T bean = (T) it.next();
  124. list.add(bean);
  125. }
  126. return list;
  127. }
  128. }

ps:工具能中用到的ObjectMapper类是Jackson库的主要类,如果要了解该类的源码以及使用方法,可自行百度。学习之路任重而道远!

发表评论

表情:
评论列表 (有 0 条评论,538人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java基础-HashMap

    1.结构 JDK1.8引入了红黑树,当链表的长度大于8,且数组的大少大于等于64时,链表会转换为红黑树。 当红黑树的结点个数小于6时,会转换为链表 ![在这里插入

    相关 java基础HashMap

    > 这几天看论坛里的大哥们都在说面试经历,无论小公司还是大公司,面试的内容有一个问题出现的概率极高,那就是问关于HashMap的实现原理、实现细节、底层实现之类的,我翻出了那本