美文网首页
Gson的使用

Gson的使用

作者: 梦沉薇露 | 来源:发表于2016-08-24 21:34 被阅读0次

1.根据键值对遍历取值

Type type = new TypeToken<ArrayList<CarBrand>>(){}.getType();
                try {
                    jsonObject =new JSONObject(string);
                       Iterator it = jsonObject.keys();  
                       // 遍历jsonObject数据,添加到Map对象  
                       while (it.hasNext())  
                       {  
                            String key = String.valueOf(it.next()); 
                            String optString = jsonObject.optString(key);
                            List<CarBrand> list = GsonUtil.getInstance().fromJson(optString, type);
                            if(list!=null &&list.size()!=0){
                            //all_list.add(object);
                            all_list.addAll(list);
                            }
                            adapter.notifyDataSetChanged();
                            //System.out.println(list);
                          
                       }  
                } catch (JSONException e) {
                    e.printStackTrace();
                }


2.将实体转为Json对象

    public static String ShoppingCart2Json(List<ShopCart> list) {
        if (list == null) {
            return "";
        }
        JSONArray array = new JSONArray();
        try {
            for (int i = 0; i < list.size(); i++) {
                JSONObject json = new JSONObject();
                ShopCart entity = list.get(i);
                if (entity != null) {
                    json.put("product_id", entity.getProduct_id());
                    json.put("number", entity.getNumber());
                    json.put("price", entity.getSpecial_price());
                    array.put(json);
                }
            }
            return array.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

相关文章

网友评论

      本文标题:Gson的使用

      本文链接:https://www.haomeiwen.com/subject/nouosttx.html