数组json串



        List<Result> datas=new ArrayList<>();


        try {
            //打开assets中的文件
            InputStream inputStream=getAssets().open("array.json");
            String str=StreamToString.streamToStr(inputStream,"utf-8");


          /*
          //第一种:gson解析  利用type
          //获取集合数据的type
            Type type= new TypeToken<List<Result>>(){}.getType();


            Gson gson=new Gson();
            datas=gson.fromJson(str,type);


            Log.d("zzz",datas.size()+"---");
            for(Result r:datas){
                Log.d("zzz",r.toString());
            }*/


         /*
         //第二种:原生解析
         try {
                JSONArray array=new JSONArray(str);
                for(int i=0;i<array.length();i++){
                    Result result=new Result();
                    JSONObject obj=array.optJSONObject(i);
                    String img3=obj.optString("img3");
                    String name=obj.optString("name");
                    double price=obj.optDouble("price");
                    double tgprice=obj.optDouble("tg_price");


                    result.setImg3(img3);
                    result.setName(name);
                    result.setPrice(price);
                    result.setTg_price(tgprice);


                    datas.add(result);


                }


            } catch (JSONException e) {
                e.printStackTrace();
            }*/




            //混合解析
            try {
                Gson gson=new Gson();


                JSONArray array=new JSONArray(str);


                for(int i=0;i<array.length();i++){
                    JSONObject object=array.optJSONObject(i);
                    Result r=gson.fromJson(object.toString(),Result.class);
                    datas.add(r);
                }




            } catch (JSONException e) {
                e.printStackTrace();
            }




        } catch (IOException e) {
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/szj_0322/article/details/79456360