错误信息com.google.gson.internal.LinkedTreeMap cannot be cast to com.



    String yxStrResult = HttpUtils.sendPost(YxUtils.url, map1);
// {"code":200,"result":"[{\"inventory\":90,\"skuId\":10040018},{\"inventory\":90,\"skuId\":10040020},{\"inventory\":0,\"skuId\":10040022},{\"inventory\":0,\"skuId\":10040023},{\"inventory\":90,\"skuId\":10308001}]"}
    Gson gosn = new Gson();
    KcGetEntity ku = gosn.fromJson(yxStrResult,KcGetEntity.class);
//ku.getResult():[{"inventory":90,"skuId":10040018},{"inventory":90,"skuId":10040020},{"inventory":0,"skuId":10040022},{"inventory":0,"skuId":10040023},{"inventory":90,"skuId":10308001}]

    List<KcGetResultEntity> ku1 = gosn.fromJson(ku.getResult(),List.class);
    for(KcGetResultEntity e: ku1){
    //以上都不会报错,当循环取值的时候 会出现上面的错误信息
            e.getInventory();
    }

正解如下:

        import com.google.gson.JsonArray;
        import com.google.gson.JsonElement;
        import com.google.gson.JsonParser;
        import com.alibaba.fastjson.JSON;
        import com.google.gson.Gson;

        List list1 = new ArrayList();  
            try {  
                Gson gson = new Gson();  
                JsonArray arry = new JsonParser().parse(ku.getResult()).getAsJsonArray();  
                        for (JsonElement jsonElement : arry) {  
                            list1.add(gson.fromJson(jsonElement, KcGetResultEntity.class));  
                        }  
                        if(list1 != null && list1.size()>0){
                            for(KcGetResultEntity kucun : list1){
                            // 此时取值就不会有错误
                                Map map2 = new HashMap();
                                map2.put("yxKc", kucun.getInventory());//库存
                                map2.put("cols1", "99999"+kucun.getSkuId());//skuId
                                map2.put("updateTime", new Date());
                                num = mallSpecDataService.updateBySkuId(map2);
                            }
                        }
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  

你可能感兴趣的:(json数据)