JAVA基礎之HashMap轉List

JAVA基礎之HashMap轉List

前言

今天在開發中,用elasticsearch java實現熱門關鍵字搜尋商品列表這樣一個功能。。。驚恐遇到一個HashMap強轉List失敗問題。這裡記錄一下~大笑

呼叫介面

這裡我先用postman調了一下通過熱門關鍵字查詢商品列表介面

發現500,伺服器內部錯誤了。。。what?因為es在阿里雲伺服器上面,本地又不能打斷點,debug除錯。檢視伺服器日誌,找到問題所在;

伺服器日誌

問題所在如下圖:

噢~~~HashMap轉強轉List失敗了。

發現問題

檢視了日誌,再看了看程式碼。

    @Override
public Map<String, Object> handleEsGoodsVipPrice(Integer uId, Map<String, Object> map) {
Map<String, Object> vipUser = vipUserMapper.queryUserVipInfoByUserId(uId);
// es查詢結果得到Map,map中取到esGoods,轉為list,處理資料後返回
List<EsGoods> list = (List<EsGoods>) map.get("esGoods");
if (vipUser != null) {
// 使用者有Vip等級
// 根據userID得到使用者vip等級ID
Integer gradeId = (Integer) vipUser.get("gradeId");
list.forEach(bsGoodsRecommendH5 -> {
BsGoodsVipPrice goodsVipPrice = goodsVipPriceMapper.queryVipPricesByGoodsIdAndVipId(bsGoodsRecommendH5.getGoodsId(), gradeId);
if (goodsVipPrice != null && goodsVipPrice.getVipPrice() != null) {
bsGoodsRecommendH5.setVipPrice(goodsVipPrice.getVipPrice());
} else {
//如果沒查到該使用者對應vip等級的vip價格  取最低Vip等級的vip價格
Long defaultVipPrice = goodsVipPriceMapper.queryDefaultVipPriceByGoodsId(bsGoodsRecommendH5.getGoodsId());
bsGoodsRecommendH5.setVipPrice(defaultVipPrice);
}
});
} else {
// 使用者沒有vip等級 vip價格預設取最低等級對應的價格
list.forEach(bsGoodsRecommendH5 -> {
Long defaultVipPrice = goodsVipPriceMapper.queryDefaultVipPriceByGoodsId(bsGoodsRecommendH5.getGoodsId());
bsGoodsRecommendH5.setVipPrice(defaultVipPrice);
});
}
map.put("esGoods", list);
return map;
}

原來就是這裡強轉出了問題

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

解決方法

呵~~既然hashMap強轉list失敗了,我就不強轉了。先把hashMap先轉為json字串,然後將得到的json字串轉為list就ok了!!!

程式碼如下:生氣

//將map.get("esGoods")先轉為json字串,然後將得到的json字串轉為list就ok了!!!
List<EsGoods> list = JsonUtils.json2ListBean(JsonUtils.toJson(map.get("esGoods")), EsGoods.class);

總結

map不能轉list??因為開發時間比較緊,日後再帶著這個問題,去尋找答案吧

附上json工具類
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wybc.common.exception.BusiException;
import com.wybc.common.model.E;
import net.sf.json.JSONArray;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.*;
/**
* Json工具類
*/
public class JsonUtils {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
mapper.setSerializationInclusion(Include.NON_NULL);
}
private JsonUtils() {
}
/**
* json字串轉換為類
*/
public static <T> T toBean(String json, Class<T> clazz) {
try {
T bean = (T) mapper.readValue(json, clazz);
return bean;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static HashMap<String, Object> toBean(String json) {
return toBean(json, HashMap.class);
}
@SuppressWarnings("unchecked")
public static HashMap<String,String> toBeanStr(String json) {
return toBean(json, HashMap.class);
}
@SuppressWarnings("unchecked")
public static <T> T toBean(String json, TypeReference<T> tr){
try {
T bean = (T) mapper.readValue(json, tr);
return bean;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 物件轉換為json字串
*/
public static String toJson(Object bean) {
String json = null;
JsonGenerator gen = null;
StringWriter sw = new StringWriter();
try {
gen = new JsonFactory().createGenerator(sw);
mapper.writeValue(gen, bean);
json = sw.toString();
} catch (IOException e) {
throw new BusiException(E.SYSTEM_ERROR);
} finally {
try {
if (gen != null) {
gen.close();
}
if (sw != null) {
sw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return json;
}
@SuppressWarnings("unchecked")
public static List<Object> toList(String json) {
return toBean(json, ArrayList.class);
}
/**
* 物件轉換為Map
*/
public static Map<String, Object> transBean2Map(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")) {
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error "   e);
}
return map;
}
/**
* json字串轉換為List
*/
public static <T> List<T>json2ListBean(String json,Class<T>cls){
JSONArray jArray= JSONArray.fromObject(json);
Collection<T> collection = JSONArray.toCollection(jArray, cls);
List<T> list = new ArrayList<T>();
Iterator<T> it = collection.iterator();
while (it.hasNext()) {
T bean = (T) it.next();
list.add(bean);
}
return list;
}
}

ps:工具能中用到的ObjectMapper類是Jackson庫的主要類,如果要了解該類的原始碼以及使用方法,可自行百度。學習之路任重而道遠!