码迷,mamicode.com
首页 > Web开发 > 详细

json数据解析,并实现将网络json数据获取用listview显示

时间:2015-01-15 23:55:08      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:

需要使用jar包

fastjson或gson这两个jar包。

//Gson的使用方式
        Gson gson=new Gson();
        String str=ReadAssetsFile.readtext(this,"json_ss");//this当前类,"json_ss"需要解析的文件名
        UserMessage userMessage=gson.fromJson(str,UserMessage.class);//需要解析的json文件最外层类名
//fastjson的使用方法
        String json=ReadAssetsFile.readtxt(this,"json_h");
        UserMessage user = JSON.parseObject(json,UserMessage.class);

以一个例子来演示:

网络数据源:

{"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},{"merchantID":"3719","name":"华庭茶府","coupon":"100元享120元小包优惠","location":"四川省成都市高新区天华路329号附1号[近天府软件园B区]","distance":"1057m","picUrl":"http://www.warmtel.com/igme_pic/1eeae0d361f54124bdd3b6600dcc6074.jpg","couponType":"YES","cardType":"YES","groupType":"NO","gpsX":104.078705,"gpsY":30.551274,"goodSayNum":0,"midSayNum":0,"badSayNum":0}]}}


//首先将数据一层层分出,写数据源的类:注:每一层所有数据都需要写出来,数据类型也必须一一对应

最外层:

public class JsonInfo {
    private int resultCode;
    private String resultInfo;
    private PageinfoMer info;

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultInfo() {
        return resultInfo;
    }

    public void setResultInfo(String resultInfo) {
        this.resultInfo = resultInfo;
    }

    public PageinfoMer getInfo() {
        return info;
    }

    public void setInfo(PageinfoMer info) {
        this.info = info;
    }
}


info这一层

public class PageinfoMer {
    private PageTotal pageInfo;
    private List<Contents> merchantKey;

    public List<Contents> getMerchantKey() {
        return merchantKey;
    }

    public void setMerchantKey(List<Contents> merchantKey) {
        this.merchantKey = merchantKey;
    }

    public PageTotal getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(PageTotal pageInfo) {
        this.pageInfo = pageInfo;
    }
}


pageInfo这层       

public class PageTotal {
    private int total;
    private int pageSize;
    private int lastPageNumber;
    private int nowPage;
    private int currNum;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getLastPageNumber() {
        return lastPageNumber;
    }

    public void setLastPageNumber(int lastPageNumber) {
        this.lastPageNumber = lastPageNumber;
    }

    public int getNowPage() {
        return nowPage;
    }

    public void setNowPage(int nowPage) {
        this.nowPage = nowPage;
    }

    public int getCurrNum() {
        return currNum;
    }

    public void setCurrNum(int currNum) {
        this.currNum = currNum;
    }
}


merchantKey这层

public class Contents {
    private String merchantID;
    private String name;
    private String coupon;
    private String location;
    private String distance;
    private String picUrl;
    private String couponType;
    private String cardType;
    private String groupType;
    private String gpsX;
    private String gpsY;
    private int goodSayNum;
    private int midSayNum;
    private int badSayNum;

    public String getMerchantID() {
        return merchantID;
    }

    public void setMerchantID(String merchantID) {
        this.merchantID = merchantID;
    }

    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 getBadSayNum() {
        return badSayNum;
    }

    public void setBadSayNum(int badSayNum) {
        this.badSayNum = badSayNum;
    }
}

可以在建一个类,将自己需要的数据在提出来

public class UserBean {
    private String name;
    private String coupon;
    private String location;
    private String distance;
    private String picUrl;
    private int couponType;
    private int cardType;
    private int groupType;

    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 int getCouponType() {
        return couponType;
    }

    public void setCouponType(int couponType) {
        this.couponType = couponType;
    }

    public int getCardType() {
        return cardType;
    }

    public void setCardType(int cardType) {
        this.cardType = cardType;
    }

    public int getGroupType() {
        return groupType;
    }

    public void setGroupType(int groupType) {
        this.groupType = groupType;
    }
}


这些数据需要在listView上显示,需要adapter适配器

listview 的xml文件和布局xml文件:

listview的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="#ffeaeeea"
        >
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff">
        <ImageView
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:src="@drawable/btn_back"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"/>
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="我的关注"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:textColor="@android:color/black"
                android:textSize="22sp"/>
    </LinearLayout>
    <ListView
            android:id="@+id/onelist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    </ListView>
</LinearLayout>


 

布局xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="6dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#ffffff">
        <ImageView
                android:id="@+id/picUrlimg"
                android:layout_width="90dp"
                android:layout_height="90dp"
                android:padding="5dp"/>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginLeft="5dp">
            <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
            <TextView
                    android:id="@+id/nametext"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@android:color/black"
                    android:textSize="17sp"
                    android:singleLine="true"
                    android:ellipsize="end"/>
            <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="5dp">
                <ImageView
                        android:id="@+id/kaimg"
                        android:layout_width="wrap_content"
                        android:layout_height="18dp"
                        android:layout_alignParentRight="true"/>
                <ImageView
                        android:id="@+id/juanimg"
                        android:layout_width="wrap_content"
                        android:layout_height="18dp"
                        android:layout_toLeftOf="@id/kaimg"/>
                <ImageView
                        android:id="@+id/tuanimg"
                        android:layout_width="wrap_content"
                        android:layout_height="18dp"
                        android:layout_toLeftOf="@id/juanimg"/>
            </RelativeLayout>
            </LinearLayout>
            <TextView
                    android:id="@+id/coupontext"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="17sp"
                    android:textColor="@android:color/holo_red_dark"
                    android:layout_marginTop="5dp"
                    android:singleLine="true"
                    android:ellipsize="end"/>
            <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                <TextView
                        android:id="@+id/locationtext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_marginBottom="5dp"
                        android:layout_marginRight="70dp"
                        android:textSize="16sp"
                        android:singleLine="true"
                        android:ellipsize="end"/>
                <TextView
                        android:id="@+id/distancetext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_alignParentRight="true"
                        android:layout_marginBottom="5dp"
                        android:layout_marginRight="5dp"
                        android:textSize="15sp"/>
                <ImageView
                        android:id="@+id/dingwei"
                        android:layout_width="18dp"
                        android:layout_height="18dp"
                        android:src="@drawable/info_map"
                        android:layout_alignParentBottom="true"
                        android:layout_marginBottom="5dp"
                        android:layout_toLeftOf="@+id/distancetext"
                        android:layout_marginRight="3dp"
                        android:layout_marginLeft="3dp"/>
            </RelativeLayout>
        </LinearLayout>
</LinearLayout>




baseadapter适配器:

public class JsonBaseAdapter extends BaseAdapter {
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private ArrayList<UserBean> arrayList=new ArrayList<UserBean>();
    public JsonBaseAdapter(Context context) {
        mContext=context;
        mLayoutInflater=LayoutInflater.from(context);
    }
    public void setdata(ArrayList<UserBean> list){
        arrayList=list;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Viewhode viewhode=null;
        if (view==null){
            viewhode=new Viewhode();
            view=mLayoutInflater.inflate(R.layout.buju,null);
            viewhode.picUrl=(ImageView)view.findViewById(R.id.picUrlimg);
            viewhode.name=(TextView)view.findViewById(R.id.nametext);
            viewhode.couponType=(ImageView)view.findViewById(R.id.juanimg);
            viewhode.cardType=(ImageView)view.findViewById(R.id.kaimg);
            viewhode.groupType=(ImageView)view.findViewById(R.id.tuanimg);
            viewhode.coupon=(TextView)view.findViewById(R.id.coupontext);
            viewhode.location=(TextView)view.findViewById(R.id.locationtext);
            viewhode.distance=(TextView)view.findViewById(R.id.distancetext);
            view.setTag(viewhode);
        }else {
            viewhode=(Viewhode)view.getTag();
        }

        viewhode.name.setText(arrayList.get(i).getName());
        viewhode.coupon.setText(arrayList.get(i).getCoupon());
        viewhode.location.setText(arrayList.get(i).getLocation());
        viewhode.distance.setText(arrayList.get(i).getDistance());

        viewhode.cardType.setImageResource(arrayList.get(i).getCardType());
        viewhode.groupType.setImageResource(arrayList.get(i).getGroupType());
        viewhode.couponType.setImageResource(arrayList.get(i).getCouponType());

        Picasso.with(mContext).load(arrayList.get(i).getPicUrl()).into(viewhode.picUrl);

        return view;
    }
    public class Viewhode{
        ImageView picUrl=null;
        TextView name=null;
        ImageView couponType=null;
        ImageView cardType=null;
        ImageView groupType=null;
        TextView coupon=null;
        TextView location=null;
        TextView distance=null;
    }

}


在activity中用流将网络去到的数据读出来,在将json数据解析出来

public class MyActivity extends Activity {
    private ListView listView;
    private JsonBaseAdapter jsonBaseAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        listView=(ListView)findViewById(R.id.onelist);
        jsonBaseAdapter=new JsonBaseAdapter(MyActivity.this);
        listView.setAdapter(jsonBaseAdapter);

        new AsyncTask<String,Void,ArrayList<UserBean>>(){
            private String url="http://192.168.1.199:8080/jj.txt";
            URL url1=null;
            InputStream is=null;
            StringBuffer sb=new StringBuffer();
            BufferedReader br=null;
            @Override
            protected ArrayList<UserBean> doInBackground(String... strings) {
                try {
                    url1=new URL(url);
                    is=url1.openStream();
                    br=new BufferedReader(new InputStreamReader(is));

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String line=null;
                try {
                    while ((line=br.readLine())!=null){
                          sb.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Gson gson=new Gson();
                Log.e("sb",sb.toString());
                JsonInfo jsonInfo=gson.fromJson(sb.toString(),JsonInfo.class);
                PageinfoMer pageinfoMer=jsonInfo.getInfo();
                ArrayList<UserBean> list=new ArrayList<UserBean>();

                   for(Contents c:pageinfoMer.getMerchantKey()){
                       UserBean u=new UserBean();
                       u.setName(c.getName());
                       u.setCoupon(c.getCoupon());
                       u.setDistance(c.getDistance());
                       u.setLocation(c.getLocation());
                       u.setPicUrl(c.getPicUrl());
                       if(c.getCardType().equals("YES")){
                           u.setCardType(R.drawable.near_card);
                       }
                       if(c.getCouponType().equals("YES")){
                           u.setCouponType(R.drawable.near_ticket);
                       }
                       if(c.getGroupType().equals("YES")){
                           u.setGroupType(R.drawable.near_group);
                       }

                    list.add(u);

                   }

                return list;
            }

            @Override
            protected void onPostExecute(ArrayList<UserBean> list) {
                    jsonBaseAdapter.setdata(list);
            }
        }.execute();
    }
}


 

附:效果图

 

json数据解析,并实现将网络json数据获取用listview显示

标签:

原文地址:http://blog.csdn.net/sinat_23134455/article/details/42747939

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!