Android之Http通信Json解析

接着http://blog.csdn.net/molu_chase/article/details/52300870这篇文章

还是将Json格式代码附上

{
    "result": 1,
    "personData": [
        {
            "name": "王晨",
            "age": 19,
            "url": "http://img06.tooopen.com/images/20160810/tooopen_sy_175027421951.jpg",
            "schoolInfos": [
                {
                    "schoolName": "南华"
                },
                {
                    "schoolName": "西桥"
                }
            ]
        },
        {
            "name": "高东",
            "age": 19,
            "url": "http://img06.tooopen.com/images/20160810/tooopen_sy_175027421951.jpg",
            "schoolInfos": [
                {
                    "schoolName": "北冥"
                },
                {
                    "schoolName": "翘楚"
                }
            ]
        }
    ]
}

解析代码如下

先是通过URL获取显示Json代码的网址,建立连接,获取输入流,读取网页内容并转成字符串传给解析函数,将解析的结果保存到List集合中,并传给适配器

public class HttpJson extends Thread {

    private String url;
    private Context context;
    private ListView listview;
    private JsonAdapter adapter;
    private Handler handler;

    public HttpJson(String url,ListView listview,JsonAdapter adapter,Handler handler){
        this.url=url;
//        this.context=context;
        this.adapter=adapter;
        this.listview=listview;
        this.handler=handler;
    }

    @Override
    public void run() {
        Log.i("info","HttpJson.run()");
        URL httpUrl= null;
        try {
            httpUrl = new URL(url);
            HttpURLConnection connection=(HttpURLConnection)httpUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
            //获得输入流,读取数据
            BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));

            StringBuffer sb=new StringBuffer();
            String str=null;

            while((str=reader.readLine())!=null){
                sb.append(str);
            }



            //解析获得的Json数据
            final List<Person> data=parseJson(sb.toString());
            //UI操作
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.setData(data);
                    listview.setAdapter(adapter);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //UI解析
    private List<Person> parseJson(String json){
        List<Person> personDataObject=null;
        try {
            //通过Json字符串获取JSONObject
            JSONObject object=new JSONObject(json);
            //获取result对应的值,如果是1,则进行解析
            int result=object.getInt("result");
            if(result==1){
                personDataObject=new ArrayList<>();

                //获取personData的数组
                JSONArray personData=object.getJSONArray("personData");

                //对数组中的元素进行解析
                for (int i=0;i<personData.length();i++){
                    Person personObject=new Person();

                    JSONObject person=personData.getJSONObject(i);
                    String name=person.getString("name");
                    int age=person.getInt("age");
                    String url=person.getString("url");

                    //将解析的结果存在list中
                    personObject.setAge(age);
                    personObject.setName(name);
                    personObject.setUrl(url);

                    //获取数组子元素的子数组,进行解析
                    List<SchoolInfo> schools=new ArrayList<>();
                    JSONArray schoolInfos=person.getJSONArray("schoolInfo");
                    for (int j=0;j<schoolInfos.length();j++){
                        JSONObject school=schoolInfos.getJSONObject(j);
                        String schoolName=school.getString("schoolName");

                        SchoolInfo schoolInfo=new SchoolInfo();
                        schoolInfo.setSchoolName(schoolName);
                        schools.add(schoolInfo);
                    }
                    personObject.setSchoolInfos(schools);
                    personDataObject.add(personObject);
                }

            }else{
//                Toast.makeText(context,"error",Toast.LENGTH_SHORT).show();

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

        return personDataObject;
    }

这里顺便附上适配器的代码,其中的List是通过上面解析Json获取的List来传入的,因此在Activity中new适配器的时候 ,只用传入context就可以了,使用的是只有一个参数的构造器

这个适配器中getView是最优化的一种写法,其中图片的获取也使用到了通过网页获取

public class JsonAdapter extends BaseAdapter {
    private List<Person> list;
    private Context context;
    private LayoutInflater inflater;

    private Handler handler=new Handler();

    public JsonAdapter(Context context,List<Person> list){
        this.list=list;
        this.context=context;
        inflater=LayoutInflater.from(context);
    }

    public JsonAdapter(Context context){
        this.context=context;
        inflater=LayoutInflater.from(context);
    }

    public void setData(List<Person> data){
        this.list=data;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       Holder holder=null;
        if(convertView==null){
            convertView=inflater.inflate(R.layout.json_item_layout,null);
            holder=new Holder(convertView);
            convertView.setTag(holder);
        }else{
            holder=(Holder)convertView.getTag();
        }

        Person person=list.get(position);
        holder.name.setText(person.getName());
        holder.age.setText(""+person.getAge());

        List<SchoolInfo> schoolInfos=person.getSchoolInfos();
        SchoolInfo schoolInfo1=schoolInfos.get(0);
        SchoolInfo schoolInfo2=schoolInfos.get(1);

        holder.school1.setText(schoolInfo1.getSchoolName());
        holder.school2.setText(schoolInfo2.getSchoolName());

        //解析网上的图片
        new HttpImage(person.getUrl(),handler,holder.imageView).start();

        return convertView;
    }

    class Holder{
        private TextView name;
        private TextView age;
        private TextView school1;
        private TextView school2;
        private ImageView imageView;

        public  Holder(View view){
            name= (TextView) view.findViewById(R.id.name);
            age= (TextView) view.findViewById(R.id.age);
            school1= (TextView) view.findViewById(R.id.school1);
            school2= (TextView) view.findViewById(R.id.school2);
            imageView= (ImageView) view.findViewById(R.id.imageView);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值