您的位置:首页 > 移动开发 > Android开发

如何使用Gson工具类,以及使用listview加载相应的解析项

2016-09-11 12:58 429 查看
使用Gson包解析数据,并添加到listview

    public class JsonWether_Activity extends AppCompatActivity {

    ListView listView;

    List<Hotel> hotellist = new ArrayList<>();

    JsonAdapter jsonAdapter;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_json_wether_layout);

        listView = (ListView) findViewById(R.id.json_listview);

        doDownLoadTxt();

        jsonAdapter = new JsonAdapter(this);

        Logs.e("mDataLists>>>>>>>>>>>>>>"+hotellist);

        jsonAdapter.SetDatalist(hotellist);

        listView.setAdapter(jsonAdapter);

    }

    /**

     * 异步获取文本信息

     */

    public void doDownLoadTxt() {

//        String txtUrl = "http://192.168.5.11:8080/json/students";

        String txtUrl = "http://192.168.5.10/serv-app/around";

        new AsyncTask<String, Void, String>() {

            @Override

            protected String doInBackground(String... params) {

                String txturl = params[0];

                return doTextByNet(txturl);

            }

            @Override

            protected void onPostExecute(String s) {

                Logs.e(s);

                doMerchantJsonParase(s);//此方法过后hotellist数据源就加载完成了

                jsonAdapter.notifyDataSetChanged();//数据更新后通知改变,保证进入页面有内容

                Logs.e(hotellist.size()+"hjhfrh");

            }

        }.execute(txtUrl);

    }

    /**

     * 解析商家json字符串

     * @param jsonStr

     */

    public void doMerchantJsonParase(String jsonStr){

        /**

         * 使用传统的方法,首先得到实例化加载数据 JSONObject jsonObject = new JSONObject(jsonStr);

         * 然后根据标签,解析相应的项   JSONObject jsonInfo = jsonObject.getJSONObject("info");

         //                             JSONArray jsonObj = jsonInfo.getJSONArray("merchantKey");

         遍历数组得到每一项   JSONObject jsonObjItem = jsonObj.getJSONObject(i);

         */

//        try {

//            JSONObject jsonObject = new JSONObject(jsonStr);

//            JSONObject jsonInfo = jsonObject.getJSONObject("info");

//            JSONArray jsonObj = jsonInfo.getJSONArray("merchantKey");

//            int length = jsonObj.length();

//            Logs.e("name        location           pictUrl");

//            for(int i = 0; i < length; i++){

//                JSONObject jsonObjItem = jsonObj.getJSONObject(i);

//                String Name = jsonObjItem.getString("name");

//                String Coupon = jsonObjItem.getString("coupon");

//

//                String Location = jsonObjItem.getString("location");

//                String Distance = jsonObjItem.getString("distance");

//                String PicUrl = jsonObjItem.getString("picUrl");

//                String CouponType = jsonObjItem.getString("couponType");

//                String CardType = jsonObjItem.getString("cardType");

//                String GroupType = jsonObjItem.getString("groupType");

//                String GpsX = jsonObjItem.getString("gpsX");

//                String GpsY = jsonObjItem.getString("gpsY");

//                int GoodSayNum = jsonObjItem.getInt("goodSayNum");

//                int MidSayNum = jsonObjItem.getInt("midSayNum");

//                int BadSayNum = jsonObjItem.getInt("badSayNum");

//                Hotel hotel = new Hotel();//每遍历一次实例化一次

//

//                hotel.setName(Name);

//                hotel.setCoupon(Coupon);

//                hotel.setLocation(Location);

//                hotel.setDistance(Distance);

//                hotel.setPicUrl(PicUrl);

//                hotel.setCouponType(CouponType);

//                hotel.setCardType(CardType);

//                hotel.setGroupType(GroupType);

//                hotel.setGpsX(GpsX);

//                hotel.setGpsY(GpsY);

//                hotel.setGoodSayNum(GoodSayNum);

//                hotel.setMidSayNum(MidSayNum);

//                hotel.setBasSayNum(BadSayNum);

//                hotellist.add(hotel);

//

//            }

//

//        } catch (JSONException e) {

//            e.printStackTrace();

//        }

        /**

         * 使用Gson工具类,首先引入工具包 file--Project Structure--app--Dependencies--"+"--library dependency(加载在线)--搜索谷歌com.google.decode.Gson就可以了

         *                                                                                  File dependency(加载离线工具包)

         *   按照数据格式{"name":12,"object":{"total":28}}

         *   由里到外依次建立相应的类,如果是数组类型的建立的类 ArrayList<Student> merchantKey 作为成员,而Student类就负责具体的数组所包含的项

         */

        Gson gson = new Gson();

        Gsons gsons = gson.fromJson(jsonStr,Gsons.class);

        Info info = gsons.getInfo();//注意info应该和Json数据里的info名称相同,否则报空指针

        ArrayList<Student> list = info.getMerchantKey();

        int length = list.size();

        Logs.e("length>>>>"+length);

        for(Student student:list){

            Hotel hotel = new Hotel();//必须写在里面,这样每遍历一次,实例化一次,hotellist加载才会得到不同的view,定义在外面,加载的都相同,并且是最后一项

            com.example.scxh.myapp.Logs.e(student.getId()+" "+student.getName()+" "+student.getCoupon()+" "+student.getCardType()+" "+student.getLocation()+" "+student.getDistance()

                    +" "+student.getPicUrl()+" "+student.getCouponType()+" "+student.getCardType()+" "+student.getGroupType()+" "

                    +student.getGpsX()+" "+student.getGpsY()+" "+student.getGoodSayNum()+" "+student.getMidSayNum()+" "+student.getBasSayNum());

                hotel.setName(student.getName());

                hotel.setCoupon(student.getCoupon());

                hotel.setLocation(student.getLocation());

                hotel.setDistance(student.getDistance());

                hotel.setPicUrl(student.getPicUrl());

                hotel.setCouponType(student.getCouponType());

                hotel.setCardType(student.getCardType());

                hotel.setGroupType(student.getGroupType());

                hotel.setGpsX(student.getGpsX());

                hotel.setGpsY(student.getGpsY());

                hotel.setGoodSayNum(student.getGoodSayNum());

                hotel.setMidSayNum(student.getMidSayNum());

                hotel.setBasSayNum(student.getBasSayNum());

                hotellist.add(hotel);

        }

    }

    /**

     * 从网络获取文本

     *

     * @param

     * @return

     */

    public String doTextByNet(String httpUrl) {

        String message = "";

        HttpURLConnection urlConnection = null;

        try {

            URL url = new URL(httpUrl);

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");  //请求方法 GET POST

//            urlConnection.setConnectTimeout(10000); //连接超时时间

//            urlConnection.setReadTimeout(15000);    //读数据超时

            urlConnection.connect();

            int code = urlConnection.getResponseCode();  //状态行:状态码 200 OK

            Logs.e("code :" + code);

            if (code == HttpURLConnection.HTTP_OK) {

                InputStream is = urlConnection.getInputStream();

                message = readInput(is);

            }

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }finally {

            urlConnection.disconnect();

        }

        return message;

    }

    public String readInput(InputStream is) {

        Reader reader = new InputStreamReader(is);  //字节转字符流

        BufferedReader br = new BufferedReader(reader); //字符缓存流

        StringBuilder sb = new StringBuilder();

        String line = null;

        try {

            while ((line = br.readLine()) != null) {

                sb.append(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                br.close();

                reader.close();

                is.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return sb.toString();

    }

    class JsonAdapter extends BaseAdapter {

        List<Hotel> list = new ArrayList<>();

        LayoutInflater layoutInflater;

        public JsonAdapter(Context context){

            this.layoutInflater = LayoutInflater.from(context);

        }

        public void SetDatalist(List<Hotel> list){

            this.list = list;

            notifyDataSetChanged();

        }

        public int getCount() {

            return list.size();

        }

        @Override

        public Object getItem(int i) {

            return list.get(i);

        }

        @Override

        public long getItemId(int i) {

            return i;

        }

        @Override

        public View getView(int i, View view, ViewGroup viewGroup) {

            HoldView holdView;

            if(view == null){

                view = layoutInflater.inflate(R.layout.activity_jsonlistview_layout,null);

                ImageView imageView = (ImageView) view.findViewById(R.id.json_listview_img);

                ImageView card = (ImageView) view.findViewById(R.id.json_card);

                ImageView group = (ImageView) view.findViewById(R.id.json_ticket);

                ImageView tuan = (ImageView) view.findViewById(R.id.json_tuan);

                TextView hotel = (TextView) view.findViewById(R.id.json_hotel);

                TextView youhui = (TextView) view.findViewById(R.id.json_youhui);

                TextView location = (TextView) view.findViewById(R.id.json_location);

                TextView distance = (TextView) view.findViewById(R.id.json_distance);

                holdView = new HoldView();

                holdView.pic = imageView;

                holdView.card = card;

                holdView.group = group;

                holdView.tuan = tuan;

                holdView.hotel = hotel;

                holdView.youhui = youhui;

                holdView.location = location;

                holdView.distance = distance;

                view.setTag(holdView);

            }

            holdView = (HoldView) view.getTag();

            Hotel hotel = (Hotel) getItem(i);

            String name= hotel.getName();

            String coupon= hotel.getCoupon();

            String location= hotel.getLocation();

            String distance= hotel.getDistance();

            String picUrl= hotel.getPicUrl();

            holdView.hotel.setText(name);

            holdView.youhui.setText(coupon);

            holdView.location.setText(location);

            holdView.distance.setText(distance);

            String couponType= hotel.getCouponType();

            String cardType= hotel.getCardType();

            String groupType= hotel.getGroupType();

            holdView.card.setImageBitmap(cardType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_card):null);//根据返回的数据“YES”或者“NO”,使用三目运算;

            holdView.group.setImageBitmap(groupType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_group):null);

            holdView.tuan.setImageBitmap(couponType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_ticket):null);

            Glide.with(JsonWether_Activity.this).load(picUrl).into(holdView.pic);//对于直接从网络取数据的图片使用第三方包,还可以缓存

            return view;

        }

    }

    public class HoldView{

        ImageView pic;

        ImageView card;

        ImageView group;

        ImageView tuan;

        TextView hotel;

        TextView youhui;

        TextView location;

        TextView distance;

    }

    class Hotel {

        int id;

        String name;

        String coupon;

        String location;

        String distance;

        String picUrl;

        String couponType;

        String cardType;

        String groupType;

        String gpsX;

        String gpsY;

        int goodSayNum;

        int midSayNum;

        int badSayNum;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

        public String getCoupon() {

            return coupon;

        }

        public void setCoupon(String coupon) {

            this.coupon = coupon;

        }

        public String getLocation() {

            return location;

        }

        public void setLocation(String location) {

            this.location = location;

        }

        public String getDistance() {

            return distance;

        }

        public void setDistance(String distance) {

            this.distance = distance;

        }

        public String getPicUrl() {

            return picUrl;

        }

        public void setPicUrl(String picUrl) {

            this.picUrl = picUrl;

        }

        public String getCouponType() {

            return couponType;

        }

        public void setCouponType(String couponType) {

            this.couponType = couponType;

        }

        public String getCardType() {

            return cardType;

        }

        public void setCardType(String cardType) {

            this.cardType = cardType;

        }

        public String getGroupType() {

            return groupType;

        }

        public void setGroupType(String groupType) {

            this.groupType = groupType;

        }

        public String getGpsX() {

            return gpsX;

        }

        public void setGpsX(String gpsX) {

            this.gpsX = gpsX;

        }

        public String getGpsY() {

            return gpsY;

        }

        public void setGpsY(String gpsY) {

            this.gpsY = gpsY;

        }

        public int getGoodSayNum() {

            return goodSayNum;

        }

        public void setGoodSayNum(int goodSayNum) {

            this.goodSayNum = goodSayNum;

        }

        public int getMidSayNum() {

            return midSayNum;

        }

        public void setMidSayNum(int midSayNum) {

            this.midSayNum = midSayNum;

        }

        public int getBasSayNum() {

            return badSayNum;

        }

        public void setBasSayNum(int badSayNum) {

            this.badSayNum = badSayNum;

        }

    }

}

-----------------------

 {"resultCode":1,

 "resultInfo":"SUCCESS",

 "info":

 {"pageInfo":{"total":28,"pageSize":10,"lastPageNumber":3,"nowPage":1,"currNum":10},

 "merchantKey":[{"merchantID":"5327","name":"瑞庭竹岛酒店","coupon":"网上预定入住可享返现优惠","location":"四川省成都市高新区老成仁路8号","distance":"203m","picUrl":"http://www.warmtel.com/igme_pic/fe3e79c1f349474b98f06477bbdc009f.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.079935,"gpsY":30.54066,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2845","name":"目咖啡软件园C6店","coupon":"凭QQ美食享咖啡8折优惠","location":"四川省成都市高新区天华二路219号天府软件园C区6号楼1楼","distance":"479m","picUrl":"http://www.warmtel.com/igme_pic/33f7ab6e385143f097527d4507cabcbe.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.078242,"gpsY":30.545434,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"5326","name":"九点国际酒店","coupon":"网上预定成功入住可返现金","location":"四川省成都市天府大道南段1号齐盛艺境[近世纪城会展中心]","distance":"556m","picUrl":"http://www.warmtel.com/igme_pic/c5721d159e63482b8a1d4dd9f70f9a03.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.077416,"gpsY":30.53835,"goodSayNum":1,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2841","name":"布衣客栈软件园店","coupon":"酒店消费券预订酒店返现金","location":"四川省成都市高新区世纪城南路399号[近天府软件园C区]","distance":"660m","picUrl":"http://www.warmtel.com/igme_pic/f8dc2d69a7b742eba4408bb72e510f5d.jpg","couponType":"YES","cardType":"YES","groupType":"NO","gpsX":104.080515,"gpsY":30.547937,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"11798","name":"茅台贵州液专卖店","coupon":"购买茅台红酒3件以上再送1件","location":"四川省成都市高新区中和镇姐儿堰路14号","distance":"683m","picUrl":"http://www.warmtel.com/igme_pic/df0a55009cea4b8ba2773278ffb3ff79.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.079227,"gpsY":30.536175,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2842","name":"巴国布衣软件园店","coupon":"持光大银行信用卡享成都巴国布衣8.8折优惠,截止2012-12-31.","location":"四川省成都市高新区世纪城南路399号","distance":"683m","picUrl":"http://www.warmtel.com/igme_pic/1f4781f9329b40218544fd4b7ec673c9.jpg","couponType":"NO","cardType":"YES","groupType":"NO","gpsX":104.080254,"gpsY":30.548117,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"5325","name":"香妃儿美容美体","coupon":"38元享980元超值美胸丰胸套餐","location":"四川省成都市高新区远大都市风景二期二号","distance":"703m","picUrl":"http://www.warmtel.com/igme_pic/26cfa2c850dd40cf9518d71ea55b687b.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.080344,"gpsY":30.535779,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"3718","name":"锦咖啡","coupon":"凭锦咖啡折扣券可享餐品8.5折,饮品7.5折,牛排6.8折优惠.\r\n\r\n1.该优惠有效期:截止至2012年12月31日;\r\n2.凭此券可以享受以下优惠:\r\n餐品8.5折\r\n饮品7.5折\r\n牛排6.8折\r\n(营业时间:09:30-23:30)\r\n\r\n展示此页即享优惠.","location":"四川省成都市高新区天华路447-1号[近天府软件园B区]","distance":"874m","picUrl":"http://www.warmtel.com/igme_pic/7629ff4f8beb43d1bd0967baba46f6c6.jpg","couponType":"YES","cardType":"YES","groupType":"NO","gpsX":104.078756,"gpsY":30.549577,"goodSayNum":3,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2416","name":"蜀国飘香远大店","coupon":"享菜品8.8折优惠(酒水除外)","location":"四川省成都市高新区远大都市风景商业街3号楼","distance":"1041m","picUrl":"http://www.warmtel.com/igme_pic/8f0e793995084f76a59cc789fb6f6c7e.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.077334,"gpsY":30.533345,"goodSayNum":0,"midSayNum":0,"badSayNum":0}

 }

-------------------------

对应Json数据相应的类

public class Gsons {

    int resultCode;

    String pageInfo;

    public Info info;

    public int getResultCode() {

        return resultCode;

    }

    public void setResultCode(int resultCode) {

        this.resultCode = resultCode;

    }

    public String getPageInfo() {

        return pageInfo;

    }

    public void setPageInfo(String pageInfo) {

        this.pageInfo = pageInfo;

    }

    public Info getInfo() {

        return info;

    }

    public void setInfo(Info info) {

        this.info = info;

    }

}

public class Info {

    public PageInfo pageInfo;

    public ArrayList<Student> merchantKey;

    public ArrayList<Student> getMerchantKey() {

        return merchantKey;

    }

    public void setMerchantKey(ArrayList<Student> merchantKey) {

        this.merchantKey = merchantKey;

    }

    public PageInfo getPageInfo() {

        return pageInfo;

    }

    public void setPageInfo(PageInfo pageInfo) {

        this.pageInfo = pageInfo;

    }

}

public class Student {

    int id;

    String name;

    String coupon;

    String location;

    String distance;

    String picUrl;

    String couponType;

    String cardType;

    String groupType;

    String gpsX;

    String gpsY;

    int goodSayNum;

    int midSayNum;

    int badSayNum;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getCoupon() {

        return coupon;

    }

    public void setCoupon(String coupon) {

        this.coupon = coupon;

    }

    public String getLocation() {

        return location;

    }

    public void setLocation(String location) {

        this.location = location;

    }

    public String getDistance() {

        return distance;

    }

    public void setDistance(String distance) {

        this.distance = distance;

    }

    public String getPicUrl() {

        return picUrl;

    }

    public void setPicUrl(String picUrl) {

        this.picUrl = picUrl;

    }

    public String getCouponType() {

        return couponType;

    }

    public void setCouponType(String couponType) {

        this.couponType = couponType;

    }

    public String getCardType() {

        return cardType;

    }

    public void setCardType(String cardType) {

        this.cardType = cardType;

    }

    public String getGroupType() {

        return groupType;

    }

    public void setGroupType(String groupType) {

        this.groupType = groupType;

    }

    public String getGpsX() {

        return gpsX;

    }

    public void setGpsX(String gpsX) {

        this.gpsX = gpsX;

    }

    public String getGpsY() {

        return gpsY;

    }

    public void setGpsY(String gpsY) {

        this.gpsY = gpsY;

    }

    public int getGoodSayNum() {

        return goodSayNum;

    }

    public void setGoodSayNum(int goodSayNum) {

        this.goodSayNum = goodSayNum;

    }

    public int getMidSayNum() {

        return midSayNum;

    }

    public void setMidSayNum(int midSayNum) {

        this.midSayNum = midSayNum;

    }

    public int getBasSayNum() {

        return badSayNum;

    }

    public void setBasSayNum(int badSayNum) {

        this.badSayNum = badSayNum;

    }

}    使用Gson包解析数据,并添加到listview

    public class JsonWether_Activity extends AppCompatActivity {

    ListView listView;

    List<Hotel> hotellist = new ArrayList<>();

    JsonAdapter jsonAdapter;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_json_wether_layout);

        listView = (ListView) findViewById(R.id.json_listview);

        doDownLoadTxt();

        jsonAdapter = new JsonAdapter(this);

        Logs.e("mDataLists>>>>>>>>>>>>>>"+hotellist);

        jsonAdapter.SetDatalist(hotellist);

        listView.setAdapter(jsonAdapter);

    }

    /**

     * 异步获取文本信息

     */

    public void doDownLoadTxt() {

//        String txtUrl = "http://192.168.5.11:8080/json/students";

        String txtUrl = "http://192.168.5.10/serv-app/around";

        new AsyncTask<String, Void, String>() {

            @Override

            protected String doInBackground(String... params) {

                String txturl = params[0];

                return doTextByNet(txturl);

            }

            @Override

            protected void onPostExecute(String s) {

                Logs.e(s);

                doMerchantJsonParase(s);//此方法过后hotellist数据源就加载完成了

                jsonAdapter.notifyDataSetChanged();//数据更新后通知改变,保证进入页面有内容

                Logs.e(hotellist.size()+"hjhfrh");

            }

        }.execute(txtUrl);

    }

    /**

     * 解析商家json字符串

     * @param jsonStr

     */

    public void doMerchantJsonParase(String jsonStr){

        /**

         * 使用传统的方法,首先得到实例化加载数据 JSONObject jsonObject = new JSONObject(jsonStr);

         * 然后根据标签,解析相应的项   JSONObject jsonInfo = jsonObject.getJSONObject("info");

         //                             JSONArray jsonObj = jsonInfo.getJSONArray("merchantKey");

         遍历数组得到每一项   JSONObject jsonObjItem = jsonObj.getJSONObject(i);

         */

//        try {

//            JSONObject jsonObject = new JSONObject(jsonStr);

//            JSONObject jsonInfo = jsonObject.getJSONObject("info");

//            JSONArray jsonObj = jsonInfo.getJSONArray("merchantKey");

//            int length = jsonObj.length();

//            Logs.e("name        location           pictUrl");

//            for(int i = 0; i < length; i++){

//                JSONObject jsonObjItem = jsonObj.getJSONObject(i);

//                String Name = jsonObjItem.getString("name");

//                String Coupon = jsonObjItem.getString("coupon");

//

//                String Location = jsonObjItem.getString("location");

//                String Distance = jsonObjItem.getString("distance");

//                String PicUrl = jsonObjItem.getString("picUrl");

//                String CouponType = jsonObjItem.getString("couponType");

//                String CardType = jsonObjItem.getString("cardType");

//                String GroupType = jsonObjItem.getString("groupType");

//                String GpsX = jsonObjItem.getString("gpsX");

//                String GpsY = jsonObjItem.getString("gpsY");

//                int GoodSayNum = jsonObjItem.getInt("goodSayNum");

//                int MidSayNum = jsonObjItem.getInt("midSayNum");

//                int BadSayNum = jsonObjItem.getInt("badSayNum");

//                Hotel hotel = new Hotel();//每遍历一次实例化一次

//

//                hotel.setName(Name);

//                hotel.setCoupon(Coupon);

//                hotel.setLocation(Location);

//                hotel.setDistance(Distance);

//                hotel.setPicUrl(PicUrl);

//                hotel.setCouponType(CouponType);

//                hotel.setCardType(CardType);

//                hotel.setGroupType(GroupType);

//                hotel.setGpsX(GpsX);

//                hotel.setGpsY(GpsY);

//                hotel.setGoodSayNum(GoodSayNum);

//                hotel.setMidSayNum(MidSayNum);

//                hotel.setBasSayNum(BadSayNum);

//                hotellist.add(hotel);

//

//            }

//

//        } catch (JSONException e) {

//            e.printStackTrace();

//        }

        /**

         * 使用Gson工具类,首先引入工具包 file--Project Structure--app--Dependencies--"+"--library dependency(加载在线)--搜索谷歌com.google.decode.Gson就可以了

         *                                                                                  File dependency(加载离线工具包)

         *   按照数据格式{"name":12,"object":{"total":28}}

         *   由里到外依次建立相应的类,如果是数组类型的建立的类 ArrayList<Student> merchantKey 作为成员,而Student类就负责具体的数组所包含的项

         */

        Gson gson = new Gson();

        Gsons gsons = gson.fromJson(jsonStr,Gsons.class);

        Info info = gsons.getInfo();

        ArrayList<Student> list = info.getMerchantKey();

        int length = list.size();

        Logs.e("length>>>>"+length);

        for(Student student:list){

            Hotel hotel = new Hotel();//必须写在里面,这样每遍历一次,实例化一次,hotellist加载才会得到不同的view,定义在外面,加载的都相同,并且是最后一项

            com.example.scxh.myapp.Logs.e(student.getId()+" "+student.getName()+" "+student.getCoupon()+" "+student.getCardType()+" "+student.getLocation()+" "+student.getDistance()

                    +" "+student.getPicUrl()+" "+student.getCouponType()+" "+student.getCardType()+" "+student.getGroupType()+" "

                    +student.getGpsX()+" "+student.getGpsY()+" "+student.getGoodSayNum()+" "+student.getMidSayNum()+" "+student.getBasSayNum());

                hotel.setName(student.getName());

                hotel.setCoupon(student.getCoupon());

                hotel.setLocation(student.getLocation());

                hotel.setDistance(student.getDistance());

                hotel.setPicUrl(student.getPicUrl());

                hotel.setCouponType(student.getCouponType());

                hotel.setCardType(student.getCardType());

                hotel.setGroupType(student.getGroupType());

                hotel.setGpsX(student.getGpsX());

                hotel.setGpsY(student.getGpsY());

                hotel.setGoodSayNum(student.getGoodSayNum());

                hotel.setMidSayNum(student.getMidSayNum());

                hotel.setBasSayNum(student.getBasSayNum());

                hotellist.add(hotel);

        }

    }

    /**

     * 从网络获取文本

     *

     * @param

     * @return

     */

    public String doTextByNet(String httpUrl) {

        String message = "";

        HttpURLConnection urlConnection = null;

        try {

            URL url = new URL(httpUrl);

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");  //请求方法 GET POST

//            urlConnection.setConnectTimeout(10000); //连接超时时间

//            urlConnection.setReadTimeout(15000);    //读数据超时

            urlConnection.connect();

            int code = urlConnection.getResponseCode();  //状态行:状态码 200 OK

            Logs.e("code :" + code);

            if (code == HttpURLConnection.HTTP_OK) {

                InputStream is = urlConnection.getInputStream();

                message = readInput(is);

            }

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }finally {

            urlConnection.disconnect();

        }

        return message;

    }

    public String readInput(InputStream is) {

        Reader reader = new InputStreamReader(is);  //字节转字符流

        BufferedReader br = new BufferedReader(reader); //字符缓存流

        StringBuilder sb = new StringBuilder();

        String line = null;

        try {

            while ((line = br.readLine()) != null) {

                sb.append(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                br.close();

                reader.close();

                is.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return sb.toString();

    }

    class JsonAdapter extends BaseAdapter {

        List<Hotel> list = new ArrayList<>();

        LayoutInflater layoutInflater;

        public JsonAdapter(Context context){

            this.layoutInflater = LayoutInflater.from(context);

        }

        public void SetDatalist(List<Hotel> list){

            this.list = list;

            notifyDataSetChanged();

        }

        public int getCount() {

            return list.size();

        }

        @Override

        public Object getItem(int i) {

            return list.get(i);

        }

        @Override

        public long getItemId(int i) {

            return i;

        }

        @Override

        public View getView(int i, View view, ViewGroup viewGroup) {

            HoldView holdView;

            if(view == null){

                view = layoutInflater.inflate(R.layout.activity_jsonlistview_layout,null);

                ImageView imageView = (ImageView) view.findViewById(R.id.json_listview_img);

                ImageView card = (ImageView) view.findViewById(R.id.json_card);

                ImageView group = (ImageView) view.findViewById(R.id.json_ticket);

                ImageView tuan = (ImageView) view.findViewById(R.id.json_tuan);

                TextView hotel = (TextView) view.findViewById(R.id.json_hotel);

                TextView youhui = (TextView) view.findViewById(R.id.json_youhui);

                TextView location = (TextView) view.findViewById(R.id.json_location);

                TextView distance = (TextView) view.findViewById(R.id.json_distance);

                holdView = new HoldView();

                holdView.pic = imageView;

                holdView.card = card;

                holdView.group = group;

                holdView.tuan = tuan;

                holdView.hotel = hotel;

                holdView.youhui = youhui;

                holdView.location = location;

                holdView.distance = distance;

                view.setTag(holdView);

            }

            holdView = (HoldView) view.getTag();

            Hotel hotel = (Hotel) getItem(i);

            String name= hotel.getName();

            String coupon= hotel.getCoupon();

            String location= hotel.getLocation();

            String distance= hotel.getDistance();

            String picUrl= hotel.getPicUrl();

            holdView.hotel.setText(name);

            holdView.youhui.setText(coupon);

            holdView.location.setText(location);

            holdView.distance.setText(distance);

            String couponType= hotel.getCouponType();

            String cardType= hotel.getCardType();

            String groupType= hotel.getGroupType();

            holdView.card.setImageBitmap(cardType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_card):null);//根据返回的数据“YES”或者“NO”,使用三目运算;

            holdView.group.setImageBitmap(groupType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_group):null);

            holdView.tuan.setImageBitmap(couponType.equals("YES")? BitmapFactory.decodeResource(getResources(),R.drawable.near_ticket):null);

            Glide.with(JsonWether_Activity.this).load(picUrl).into(holdView.pic);//对于直接从网络取数据的图片使用第三方包,还可以缓存

            return view;

        }

    }

    public class HoldView{

        ImageView pic;

        ImageView card;

        ImageView group;

        ImageView tuan;

        TextView hotel;

        TextView youhui;

        TextView location;

        TextView distance;

    }

    class Hotel {

        int id;

        String name;

        String coupon;

        String location;

        String distance;

        String picUrl;

        String couponType;

        String cardType;

        String groupType;

        String gpsX;

        String gpsY;

        int goodSayNum;

        int midSayNum;

        int badSayNum;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

        public String getCoupon() {

            return coupon;

        }

        public void setCoupon(String coupon) {

            this.coupon = coupon;

        }

        public String getLocation() {

            return location;

        }

        public void setLocation(String location) {

            this.location = location;

        }

        public String getDistance() {

            return distance;

        }

        public void setDistance(String distance) {

            this.distance = distance;

        }

        public String getPicUrl() {

            return picUrl;

        }

        public void setPicUrl(String picUrl) {

            this.picUrl = picUrl;

        }

        public String getCouponType() {

            return couponType;

        }

        public void setCouponType(String couponType) {

            this.couponType = couponType;

        }

        public String getCardType() {

            return cardType;

        }

        public void setCardType(String cardType) {

            this.cardType = cardType;

        }

        public String getGroupType() {

            return groupType;

        }

        public void setGroupType(String groupType) {

            this.groupType = groupType;

        }

        public String getGpsX() {

            return gpsX;

        }

        public void setGpsX(String gpsX) {

            this.gpsX = gpsX;

        }

        public String getGpsY() {

            return gpsY;

        }

        public void setGpsY(String gpsY) {

            this.gpsY = gpsY;

        }

        public int getGoodSayNum() {

            return goodSayNum;

        }

        public void setGoodSayNum(int goodSayNum) {

            this.goodSayNum = goodSayNum;

        }

        public int getMidSayNum() {

            return midSayNum;

        }

        public void setMidSayNum(int midSayNum) {

            this.midSayNum = midSayNum;

        }

        public int getBasSayNum() {

            return badSayNum;

        }

        public void setBasSayNum(int badSayNum) {

            this.badSayNum = badSayNum;

        }

    }

}

-----------------------

 {"resultCode":1,

 "resultInfo":"SUCCESS",

 "info":

 {"pageInfo":{"total":28,"pageSize":10,"lastPageNumber":3,"nowPage":1,"currNum":10},

 "merchantKey":[{"merchantID":"5327","name":"瑞庭竹岛酒店","coupon":"网上预定入住可享返现优惠","location":"四川省成都市高新区老成仁路8号","distance":"203m","picUrl":"http://www.warmtel.com/igme_pic/fe3e79c1f349474b98f06477bbdc009f.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.079935,"gpsY":30.54066,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2845","name":"目咖啡软件园C6店","coupon":"凭QQ美食享咖啡8折优惠","location":"四川省成都市高新区天华二路219号天府软件园C区6号楼1楼","distance":"479m","picUrl":"http://www.warmtel.com/igme_pic/33f7ab6e385143f097527d4507cabcbe.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.078242,"gpsY":30.545434,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"5326","name":"九点国际酒店","coupon":"网上预定成功入住可返现金","location":"四川省成都市天府大道南段1号齐盛艺境[近世纪城会展中心]","distance":"556m","picUrl":"http://www.warmtel.com/igme_pic/c5721d159e63482b8a1d4dd9f70f9a03.jpg","couponType":"YES","cardType":"NO","groupType":"NO","gpsX":104.077416,"gpsY":30.53835,"goodSayNum":1,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2841","name":"布衣客栈软件园店","coupon":"酒店消费券预订酒店返现金","location":"四川省成都市高新区世纪城南路399号[近天府软件园C区]","distance":"660m","picUrl":"http://www.warmtel.com/igme_pic/f8dc2d69a7b742eba4408bb72e510f5d.jpg","couponType":"YES","cardType":"YES","groupType":"NO","gpsX":104.080515,"gpsY":30.547937,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"11798","name":"茅台贵州液专卖店","coupon":"购买茅台红酒3件以上再送1件","location":"四川省成都市高新区中和镇姐儿堰路14号","distance":"683m","picUrl":"http://www.warmtel.com/igme_pic/df0a55009cea4b8ba2773278ffb3ff79.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.079227,"gpsY":30.536175,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2842","name":"巴国布衣软件园店","coupon":"持光大银行信用卡享成都巴国布衣8.8折优惠,截止2012-12-31.","location":"四川省成都市高新区世纪城南路399号","distance":"683m","picUrl":"http://www.warmtel.com/igme_pic/1f4781f9329b40218544fd4b7ec673c9.jpg","couponType":"NO","cardType":"YES","groupType":"NO","gpsX":104.080254,"gpsY":30.548117,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"5325","name":"香妃儿美容美体","coupon":"38元享980元超值美胸丰胸套餐","location":"四川省成都市高新区远大都市风景二期二号","distance":"703m","picUrl":"http://www.warmtel.com/igme_pic/26cfa2c850dd40cf9518d71ea55b687b.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.080344,"gpsY":30.535779,"goodSayNum":0,"midSayNum":0,"badSayNum":0},

 {"merchantID":"3718","name":"锦咖啡","coupon":"凭锦咖啡折扣券可享餐品8.5折,饮品7.5折,牛排6.8折优惠.\r\n\r\n1.该优惠有效期:截止至2012年12月31日;\r\n2.凭此券可以享受以下优惠:\r\n餐品8.5折\r\n饮品7.5折\r\n牛排6.8折\r\n(营业时间:09:30-23:30)\r\n\r\n展示此页即享优惠.","location":"四川省成都市高新区天华路447-1号[近天府软件园B区]","distance":"874m","picUrl":"http://www.warmtel.com/igme_pic/7629ff4f8beb43d1bd0967baba46f6c6.jpg","couponType":"YES","cardType":"YES","groupType":"NO","gpsX":104.078756,"gpsY":30.549577,"goodSayNum":3,"midSayNum":0,"badSayNum":0},

 {"merchantID":"2416","name":"蜀国飘香远大店","coupon":"享菜品8.8折优惠(酒水除外)","location":"四川省成都市高新区远大都市风景商业街3号楼","distance":"1041m","picUrl":"http://www.warmtel.com/igme_pic/8f0e793995084f76a59cc789fb6f6c7e.jpg","couponType":"NO","cardType":"NO","groupType":"NO","gpsX":104.077334,"gpsY":30.533345,"goodSayNum":0,"midSayNum":0,"badSayNum":0}

 }

-------------------------

对应Json数据相应的类

public class Gsons {

    int resultCode;

    String pageInfo;

    public Info info;

    public int getResultCode() {

        return resultCode;

    }

    public void setResultCode(int resultCode) {

        this.resultCode = resultCode;

    }

    public String getPageInfo() {

        return pageInfo;

    }

    public void setPageInfo(String pageInfo) {

        this.pageInfo = pageInfo;

    }

    public Info getInfo() {

        return info;

    }

    public void setInfo(Info info) {

        this.info = info;

    }

}

public class Info {

    public PageInfo pageInfo;

    public ArrayList<Student> merchantKey;

    public ArrayList<Student> getMerchantKey() {

        return merchantKey;

    }

    public void setMerchantKey(ArrayList<Student> merchantKey) {

        this.merchantKey = merchantKey;

    }

    public PageInfo getPageInfo() {

        return pageInfo;

    }

    public void setPageInfo(PageInfo pageInfo) {

        this.pageInfo = pageInfo;

    }

}

public class Student {

    int id;

    String name;

    String coupon;

    String location;

    String distance;

    String picUrl;

    String couponType;

    String cardType;

    String groupType;

    String gpsX;

    String gpsY;

    int goodSayNum;

    int midSayNum;

    int badSayNum;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getCoupon() {

        return coupon;

    }

    public void setCoupon(String coupon) {

        this.coupon = coupon;

    }

    public String getLocation() {

        return location;

    }

    public void setLocation(String location) {

        this.location = location;

    }

    public String getDistance() {

        return distance;

    }

    public void setDistance(String distance) {

        this.distance = distance;

    }

    public String getPicUrl() {

        return picUrl;

    }

    public void setPicUrl(String picUrl) {

        this.picUrl = picUrl;

    }

    public String getCouponType() {

        return couponType;

    }

    public void setCouponType(String couponType) {

        this.couponType = couponType;

    }

    public String getCardType() {

        return cardType;

    }

    public void setCardType(String cardType) {

        this.cardType = cardType;

    }

    public String getGroupType() {

        return groupType;

    }

    public void setGroupType(String groupType) {

        this.groupType = groupType;

    }

    public String getGpsX() {

        return gpsX;

    }

    public void setGpsX(String gpsX) {

        this.gpsX = gpsX;

    }

    public String getGpsY() {

        return gpsY;

    }

    public void setGpsY(String gpsY) {

        this.gpsY = gpsY;

    }

    public int getGoodSayNum() {

        return goodSayNum;

    }

    public void setGoodSayNum(int goodSayNum) {

        this.goodSayNum = goodSayNum;

    }

    public int getMidSayNum() {

        return midSayNum;

    }

    public void setMidSayNum(int midSayNum) {

        this.midSayNum = midSayNum;

    }

    public int getBasSayNum() {

        return badSayNum;

    }

    public void setBasSayNum(int badSayNum) {

        this.badSayNum = badSayNum;

    }

}



顶0踩0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android gson listview