JAVA基础之HashMap转List

前言

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

调用接口

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

JAVA基础之HashMap转List_第1张图片

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

服务器日志

问题所在如下图:

JAVA基础之HashMap转List_第2张图片

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

发现问题

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

    @Override
    public Map handleEsGoodsVipPrice(Integer uId, Map map) {
        Map vipUser = vipUserMapper.queryUserVipInfoByUserId(uId);
        // es查询结果得到Map,map中取到esGoods,转为list,处理数据后返回
        List list = (List) 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 list = (List) map.get("esGoods");

解决方法

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

代码如下:

//将map.get("esGoods")先转为json字符串,然后将得到的json字符串转为list就ok了!!!
List 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 toBean(String json, Class clazz) {
		try {
			T bean = (T) mapper.readValue(json, clazz);
			return bean;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static HashMap toBean(String json) {
		return toBean(json, HashMap.class);
	}

	@SuppressWarnings("unchecked")
	public static HashMap toBeanStr(String json) {
		return toBean(json, HashMap.class);
	}
	
	@SuppressWarnings("unchecked")
	public static  T toBean(String json, TypeReference 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 toList(String json) {
		return toBean(json, ArrayList.class);
	}

	/**
	 * 对象转换为Map
	 */
	public static Map transBean2Map(Object obj) {
		if (obj == null) {
			return null;
		}
		Map map = new HashMap();
		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  Listjson2ListBean(String json,Classcls){
		JSONArray jArray= JSONArray.fromObject(json);
	    Collection collection = JSONArray.toCollection(jArray, cls);
	    List list = new ArrayList();
	    Iterator it = collection.iterator();
	    while (it.hasNext()) {
	        T bean = (T) it.next();
	        list.add(bean);
	    }
	    return list;
	}
} 
  

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

你可能感兴趣的:(日常杂记)